Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on a Byte

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?

like image 754
Cactus Avatar asked Jan 05 '23 01:01

Cactus


1 Answers

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."

like image 168
ruakh Avatar answered Jan 14 '23 06:01

ruakh