How prevent type inference?

I found temporary workaround for those who are ready to possible future refactoring.
It may be kotlin compiler or ide bug:

  1. Create file kotlin/internal/Annotations.kt in source root of your project:
package kotlin.internal

@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.BINARY)
annotation class Exact
  1. Add compiler command line parameter: -Xallow-kotlin-package
  2. Using this annotation:
import kotlin.internal.Exact

open class Foo(val barInt: Int)

// public interface KProperty1<T, out R> : KProperty<R>, (T) -> R

fun <E : Foo, T> test(field: kotlin.reflect.KProperty1<E, @Exact T>, value: T): T = TODO()


fun main(args: Array<String>) {
    test(Foo::barInt, 123) // ok
    test(Foo::barInt, "NotInt") // expected compile error:
    /*
        Error:(13, 5) Kotlin: Type inference failed: Cannot infer type parameter T in fun <E : Foo, T> test(field: KProperty1<E, T>, value: T): T
        None of the following substitutions
        (KProperty1<Foo, Int>,Int)
        (KProperty1<Foo, String>,String)
        can be applied to
        (KProperty1<Foo, Int>,String)
    */
}
4 Likes