Is there any way to compare two generic objects like with JAVA Comparable?

Viewed 412

Is there any way to compare two objects like with JAVA Comparable?

val o1: Any
val o2: Any

I know they are the same class and implement JAVA Comparable. If I cast them to JAVA Comparable I get warning I should use Kotlin Comparable, but Kotlin version needs Type which is not known at compile time. All I need is something like this:

val result = (o1 as Comparable).compareTo(o2)
2 Answers

You can use Comparable<Any>. It will complain of an unchecked cast, which you can suppress since you know it's safe if the types match.

val o1: Any = 2
val o2: Any = 4
if (o1 is Comparable<*> && o1::class == o2::class) {
    @Suppress("UNCHECKED_CAST")
    if (o1 as Comparable<Any> < o2) {
        println("it's less")
    }
}

Try with:

val result = (o1 as Comparable<*>).compareTo(o2)

that should work.

Related