How can I switch on a Byte
value? The obvious way would be:
fun foo(b: Byte): Boolean {
return when(b) {
0 -> true
else -> false
}
}
but that fails at compile time with
src/ByteSwitch.kt:3:5: error: incompatible types: kotlin.Int and kotlin.Byte
0 -> true
^
Is there a way to make that 0
be a byte literal?
Since Kotlin allows branch conditions to be arbitrary expressions (not necessarily constants), one approach is to accept that the 0
will be an Int
and simply convert it explicitly to a Byte
:
fun foo(b: Byte): Boolean {
return when(b) {
0.toByte() -> true
else -> false
}
}
Per Ilya, "0.toByte()
is evaluated at compile time, so there's no cost of conversion at runtime."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With