Hi, i have some problem with generic types. Maybe ...
# announcements
a
Hi, i have some problem with generic types. Maybe someone can help me out. Consider the following code
Copy code
class MyClass<T : Comparable<T>> {
    fun join(other : MyClass<T>) {
        // so some stuff
    }
}

fun someFunction(a : Any, b : Any) {
    val instanceA = a as MyClass<*>
    val instanceB = b as MyClass<*>

    instanceA.join(instanceB)
}
s
These two work:
Copy code
fun <T: Comparable<T>> someFunction2(a : T, b : T) {
    val instanceA = a as MyClass<T>
    val instanceB = b as MyClass<T>
    instanceA.join(instanceB)
}

fun someFunction3(a : Any, b : Any) {
    val instanceA = a as MyClass<Comparable<Comparable<*>>>
    val instanceB = b as MyClass<Comparable<Comparable<*>>>
    instanceA.join(instanceB)
}
(both use unsafe type-casts; you can pass values to
a
and
b
that will make these two throw an exception)
a
Also you could change
join
method signature like this
Copy code
fun join(other : MyClass<*>)
and this works as well. But signature change may not cover all your usecases of
join
ofcourse.
a
I can't someFunction2, the signature should express the constraint that I don't know anything about the type and even don't have a type paramter. But someFunction3 does the trick, thanks Anton. In the meantime I used what Alexander suggested but it had some other drawbacks.
k
I'm kinda confused why 3 works