Is there a way to do a when directly on bytes? or ...
# announcements
Is there a way to do a when directly on bytes? or do I always have to convert to Int?
✔️ 1
It should work for any type, I think. Does it throw any error for you?
Make sure you’re using
on the literal in your
and it should work.
Copy code
when(b) {
  0.toByte() -> true
  else -> false
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… }
Understood. If we’re being pedantic about it, using
in the when clause is handled at compile time, so it’s technically fewer operations, even though it’s a bit uglier. But
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.
yeah I'm also not that concerned with speed here, but I was wondering if there was an "accepted" way
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
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