Klitos Kyriacou
04/04/2025, 4:18 PMFoo
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:
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:
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.Youssef Shoaib [MOD]
04/04/2025, 4:26 PMfun main() {
val (left, right) = getValues()
left as Comparable<Any?>
right as Comparable<Any?>
val foo = Foo<Comparable<Any?>>()
foo.process(left, right)
}
Klitos Kyriacou
04/04/2025, 4:28 PM