Using Java I may want to initialize a final variable using a switch statement:
final String finalValue;
switch (condition) {
case 1:
finalValue = "One";
break;
case 2:
finalValue = "Two";
break;
case 3:
finalValue = "Three";
break;
default:
finalValue = "Undefined";
break;
}
In Kotlin, trying to do the same:
val finalValue: String
when (condition) {
1 -> finalValue = "One"
2 -> finalValue = "Two"
3 -> finalValue = "Three"
else -> finalValue = "Undefined"
}
result in a compilation error.
A solutions is using the by lazy
combination, but this create a new Lazy
instance.
val finalValue: String by lazy {
when (condition) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Undefined"
}
}
Is there a better way to accomplish this?
How about this construction:
val finalValue: String = when (condition) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Undefined"
}
Using when
as an expression.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With