So let me explain the context to see if I understand it correctly.
When we are using when expression without a subject, branch condition is satisfied when condition is true.
when {
input is UUID -> "is UUID"
isUUID(input) -> "is UUID in String"
else -> "is somethin else"
}.also { println(it) }// "is UUID in String"
But when we are using subject in when, this no longer applies. The branch condition also has to correlate to the subject. If not, the branch is skipped even when after evaluation it is true.
when (input) {
is UUID -> "is UUID"
isUUID(input) -> "is UUID in String"
true -> "is true"
else -> "is somethin else"
}.also { println(it) }// "is something else"
If that’s the case, it would be nice if IntelliJ IDEA could gray out those branches with a warning message or it can lead to an unexpected behaviour.
I didn’t see this explanation in documentation.
Whole code:
import java.util.*
fun main() {
val input: Any = "8777de13-b14c-4bed-83c0-0c8ab5cf0755"
println(isUUID(input))// true
// expected behaviour
when {
input is UUID -> "is UUID"
isUUID(input) -> "is UUID in String"
else -> "is somethin else"
}.also { println(it) }// "is UUID in String"
// unexpected behaviour
when (input) {
is UUID -> "is UUID"
isUUID(input) -> "is UUID in String"
true -> "is true"
else -> "is somethin else"
}.also { println(it) }// "is something else"
}
fun isUUID(uuid: Any): Boolean {
return uuid is String && isStringUUID(uuid)
}
fun isStringUUID(id: String): Boolean {
try {
UUID.fromString(id)
return true
} catch (exception: IllegalArgumentException) {
return false
}
}