Is there a way to make Kotlin raise an error if th...
# getting-started
k
Is there a way to make Kotlin raise an error if the amount of components in
val (a, b) = list
is too few? Python does it, and it's weird that Kotlin is the more unsafe one.
a
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS45LjI1IiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncy[…]xpc3RPZigxKVxuICAgIFxuICAgIHZhbCAoYSwgYikgPSBpbnB1dFxufSJ9 I get a ListOutOfBounds error, which makes sense. Or do you mean the other way around? If so, what is 'unsafe' about it?
k
I mean the other way around yeah. You don't get an error if your data isn't the shape the way you wanted. Which usually means your code is wrong
a
This just isn't how destructing works in Kotlin, it does not imply unsafety. But you can add a
require { list.length == 2}
in front.
m
Kotlin just builds a destructured list based on the componentN() functions. Funnily enough, I'd rather have them be even more lenient by making them lazy. e.g. if I have a list of arguments:
[false, 1, 3]
or
[true]
then I want to able to do
(arg1, arg2, arg3) -> if(arg1){ null } else { arg2..arg3 }
perhaps a compiler plugin can make the destructuring based on your requirements?
k
I made a compiler plugin yeah