According to the documentation for When Expression, it can replace "if-else if", so I tried implementing a function to return maximum of two variable of Any type:
fun maxOf(a: Any, b: Any) = when {
a is Int && b is Int -> if (a < b) b else a
a is Double && b is Double -> if (a < b) b else a
a is Int && b is Double -> if (a < b) b else a
a is Double && b is Int -> if (a < b) b else a
a is String && b is String -> if (a < b) b else a
else -> null
}
The above implementation works but I thought it could be more concise:
fun maxOf(a: Any, b: Any) = when {
(a is Int || a is Double) && (b is Int || b is Double) -> if (a < b) b else a
a is String && b is String -> if (a < b) b else a
else -> null
}
But I failed because the second implementation doesn't work; the error is in the first occurrence of if (a < b):
Unresolved references.
None of the following candidates is applicable because of receiver type mismatch
• public fun String.compareTo(other: String, ignoreCase: Boolean =...): Int defined in kotlin.text
Is this because smart-cast is not capable of casting a and b to their actual types after evaluating the expression (a is Int || a is Double) && (b is Int || b is Double)? Or am I missing something?
Update
The same error happens even if the type of a and b is changed to Number:
fun maxOf(a: Number, b: Number) = when {
(a is Int || a is Double) && (b is Int || b is Double) -> if (a < b) b else a
else -> null
}