7

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?

Cactus
  • 27,075
  • 9
  • 69
  • 149

2 Answers2

10

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

Community
  • 1
  • 1
ruakh
  • 175,680
  • 26
  • 273
  • 307
2

You cannot specify a byte literal in Kotlin (nor can you in Java). From Literal Constants - Basic Types - Kotlin Programming Language

There are the following kinds of literal constants for integral values:

  • Decimals: 123
    • Longs are tagged by a capital L: 123L
  • Hexadecimals: 0x0F
  • Binaries: 0b00001011

You can however declare compiler-time constants to avoid run-time overhead:

const val ZERO_BYTE: Byte = 0

fun foo(b: Byte): Boolean {
    return when (b) {
        ZERO_BYTE -> true
        else -> false
    }
}

Inspecting the Kotlin bytecode further reveals that as 0.toByte() can be determined at compile-time you can in fact inline the evaluation with no additional run-time overhead:

fun foo(b: Byte): Boolean {
    return when (b) {
        0.toByte() -> true
        else -> false
    }
}
mfulton26
  • 29,956
  • 6
  • 64
  • 88