Maybe it's too late in the day and I'm getting my ...
# getting-started
k
Maybe it's too late in the day and I'm getting my brain fried trying to work with generics. Here's a minimal example to explain my problem. I have a class
Foo
that has a member function
process
that takes two generic parameters, which must be
Comparable
. I need to call this member function and pass two
Comparable
parameters of the same type, but these could be any
Comparable
type. How can I do this? I want to avoid a very long and incomplete
when
statement:
Copy code
class Foo<T : Comparable<T>> {
    fun process(left: T, right: T) {
        val comparisonResult = left.compareTo(right)
        TODO()
    }
}

// Returns values of the same type, but we don't know at compile time which type.
// This is a third-party function and I have no access to the source.
fun getValues(): List<Any> { TODO() }

fun main() {
    val (left, right) = getValues()
    when {
        left is Int && right is Int -> {
            val foo = Foo<Int>()
            foo.process(left, right)
        }
        left is Long && right is Long -> {
            val foo = Foo<Long>()
            foo.process(left, right)
        }
        left is String && right is String -> {
            val foo = Foo<String>()
            foo.process(left, right)
        }
        left is BigDecimal && right is BigDecimal -> {
            val foo = Foo<BigDecimal>()
            foo.process(left, right)
        }
    }
}
I can't find a way to do it generically:
Copy code
val foo = Foo<*>()  // Error. Also val foo = Foo<Comparable<*>>() is also an error.
foo.process(left, right)
If I were using Java, I could do this easily using raw types.
y
This works:
Copy code
fun main() {
    val (left, right) = getValues()
    left as Comparable<Any?>
    right as Comparable<Any?>
    val foo = Foo<Comparable<Any?>>()
    foo.process(left, right)
}
👍 1
thank you color 1
k
Thanks, I don't know why I didn't think of that!