Would be nice if there was some compact way to cla...
# announcements
n
Would be nice if there was some compact way to claim to a when statement that something is exhausive when the compiler cannot see that it is:
Copy code
return when(Math.floorMod(value / 90 * rot.dir, 4)) {
        0 -> vector
        1 -> Point(-vector.j, vector.i)
        2 -> Point(-vector.i, -vector.j)
        3 -> Point(vector.j,-vector.i)
        else -> throw Exception("impossible")
    }
THe compiler here forces me to have the else. And I can't even have an assert False in the else, because that doesn't type check, I have to throw an exception which forces me to make up a name. Maybe something like !else at the end of the when or something like that. Or maybe some kind of special function with a contract that lets you do modulus where the compiler knows that only 0 to N-1 are possible outputs
r
If it’s like Java, assert false just throws an AssertionError, so you could do that to save making up a new Exception type name.
a
I believe
error("impossible")
should also work
f
I usually use
Copy code
fun rotateRight(times: Int): Pos {
        return when (times % 4) {
            0 -> this
            1 -> Pos(-y, x)
            2 -> Pos(-x, -y)
            3 -> Pos(y, -x)
            else -> error("unable to rotate $this $times times")
        }
    }
I think the
error
looks ok; not quite so overwhelming as the
Throw Exception
, and more than once it has triggered after I changed my code. Even though it wasn’t possible when I wrote -it could be possible after changing it.
n
Your error message is misleading though
it's literally unreachable code
well, it's not unreachable because kotlin's % operator doesn't have the good behavior 🙂 but with Math.floorMod it's unreachable
for me assert(false) doesn't work because assert returns unit
b
Setup a sealed class with concrete types for the 0-3 range and it becomes exhaustive. Can keep it hidden/private and only use it internally in the function with a mapper in the when
Can also IntRange the arg as well iirc
n
A sealed class is a ton of boilerplate to achieve this
Not sure what the intrange approach would look like exactly