andreasmattsson
05/03/2021, 4:02 PMdata class TestContainer(
val body: Any?
)
operator fun TestContainer?.compareTo(b: TestContainer?): Int = this?.body.let { aBody ->
b?.body.let { bBody ->
when {
aBody is Boolean && bBody is Boolean -> {
val aBoolean: Boolean = aBody
val bBoolean: Boolean = bBody
return aBoolean.compareTo(bBoolean)
}
else -> -1
}
}
}
fun main() {
println("Comparison: ${TestContainer(true) < TestContainer(false)}")
}
But the following yields ClassCastException at runtime on JVM?
data class TestContainer(
val body: Any?
)
operator fun TestContainer?.compareTo(b: TestContainer?): Int = this?.body.let { aBody ->
b?.body.let { bBody ->
when {
aBody is Boolean && bBody is Boolean -> aBody.compareTo(bBody)
else -> -1
}
}
}
fun main() {
println("Comparison: ${TestContainer(true) < TestContainer(false)}")
}
Error is
Exception in thread "main" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
I'd expect the two to be equivalent due to smart cast?andreasmattsson
05/03/2021, 4:04 PMandreasmattsson
05/03/2021, 4:05 PMTobias Berger
05/04/2021, 2:01 PM(Boolean)aBody
you get ((Number)aBody).intValue()
andreasmattsson
05/04/2021, 6:29 PM