Is there a way to do a when directly on bytes? or ...
# announcements
b
Is there a way to do a when directly on bytes? or do I always have to convert to Int?
✔️ 1
c
It should work for any type, I think. Does it throw any error for you?
b
Make sure you’re using
.toByte()
on the literal in your
when
and it should work.
E.g.:
Copy code
when(b) {
  0.toByte() -> true
  else -> false
}
b
Ok I just wanted to know if there was a way to write bytes in a shorter way
I've been doing when(b.toInt()) { 0 -> true… }
b
Understood. If we’re being pedantic about it, using
<literal>.toByte()
in the when clause is handled at compile time, so it’s technically fewer operations, even though it’s a bit uglier. But
.toInt()
is an extremely fast operation, so it’s not a big deal. Like I said, pedantic 🙂 I’d say go with whichever one looks better.
b
yeah I'm also not that concerned with speed here, but I was wondering if there was an "accepted" way
b
Not especially, no. One other suggestion to consider might be to stick the values in constants so you have names for the bytes, e.g.
Copy code
const val NULL_BYTE: Byte = 0
Depending on why you’re using a
when
on a byte to begin with, this may improve readability. Other than that, there’s no way to declare specify a byte literal in Kotlin, so do whatever makes the most sense for your code and you should be good.
👍 1