Why is it that the following code has no errors: `...
# announcements
a
Why is it that the following code has no errors:
Copy code
fun calculateNumberOfLengthBytes(data: ByteArray): Int {
    val l: Int = data.size
    return when {
        l < 128 -> 1
        l < 16384 -> 2
        l < 2097152 -> 3
        l < 268435456 -> 4
        else -> 5
    }
}
but, the following complains about "Incompatible types: Boolean and Int" in the comparisons
Copy code
val data = byteArrayOf(5, 6, 7)
when(val l: Int = data.size) {
    l < 128 -> 1
    l < 16384 -> 2
    l < 2097152 -> 3
    l < 268435456 -> 4
    else -> 5
}
d
I'm not sure that you can use
: Int
in this location of a when expression, I don't think I've seen it.
a
When I take it out I get the same result. I have only seen the variable from the val being used on the right hand side of the -> in examples. Pity one cant say something like
Copy code
when(data.size) {
  < 20 -> 1
...
I won't want to write a parser for that though :)
a
Because the latter checks strongly against Int val, it must have ints on the left side.
a
ah... the val is implicitly used on the left hand side right? So am I correct that the statement like l < 128 is seen as a Boolean expression and then compared with the val which is of type int?
a
That's correct
a
Thanks!
👍 1