Set generics inference upper limit?


#1

Consider the following function:

fun <T> doSomething(x1: T, x2: T) {
}

I expect, that both parameters will be of the same type not equal to Any. But when calling with totally different parameters, Any is being inferred and the following becomes totally legal:

doSomething("string", 0)

Is there any way to set an upper limit type or some other way to solve this within the single function?


#2

There is currently no way to constrain a type parameter so that multiple references to it all refer to the same type - in either Kotlin or Java.

However, you can cut down the possibilities by specifying that ‘T’ must inherit from another class (Number, perhaps, in your example) or must implement some interface.

So to prevent a String being assigned to x1 you could do:

fun <T : Number> doSomething(x1: T, x2: T) {}

I hope in due course other generic constraints will be added to the language though they probably won’t be unless they’re added to the JVM first or are restricted to inline functions.


#3

Thanks, Alan. Unfortunately, I can’t set any constraint there :frowning: I already thought about this option
The only option, for now, is to implement some two-step builder-like solution (i.e. with(x1).do(x2)), not a single function call.


#4

there any way to set an upper limit type or some other way to solve this within the single function?

No, there’s no such way at this moment.

See https://youtrack.jetbrains.com/issue/KT-13198 for details. It would help if you could describe your concrete use case there.


#5

Thank you, Ilya. My case is already there! It’s also connected with KProperty1