Partial generic type resolution

I would love Kotlin to support partial generic type resolution. I mean it would be nice if we only had to provide generic parameters that could not be resolved based on the call site. An example - although fabricated for simplicity - would be a generic extension function to a generic extension target wich type can always be resolved at the call site:

inline fun <T, reified X> T.unsafeCast(): X = X::class.java.cast(this)

fun test() {
    val a: String = "".unsafeCast()  // will compile
    val b = "".unsafeCast<String>()  // will not compile
}

Maybe Kotlin could resolve generic types from left to right as far as possible and allow to provide the rest needed or provided.

1 Like

I don’t know if this helps, but your problem is more because if you give type arguments, you must give all. T is kinda useless in your example. This works fine:

inline fun <reified X> Any?.unsafeCast(): X = X::class.java.cast(this)

fun test() {
    val a: String = "".unsafeCast()  // will compile
    val b = "".unsafeCast<String>()  // will compile
}
1 Like

You are right. This would work. Unless T would be reified to allow processing of type in case of null values right?

I have hit several point where partial resolution would be a great help.

Looks like there are some open feature requests proposing something similar: https://youtrack.jetbrains.com/issue/KT-13394

But as far as I know there is no actual KEEP for this yet. Maybe someone could create one :slight_smile:

1 Like

I will have to take a look but it sure sounds promising. Thanks. Maybe I will also be able took write a keep. Always wanted to contribute to Kotlin.