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.
You can also use init block to initialize a final variable.
val finalValue: String
init {
finalValue = when (condition) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Undefined"
}
}
Actually, the following does compile, I'm not sure which problem you encountered?
fun x(condition: Int = 5) {
val finalValue: String
when (condition) {
1 -> finalValue = "One"
2 -> finalValue = "Two"
3 -> finalValue = "Three"
else -> finalValue = "Undefined"
}
}
The only possibility to me: You wrote the when
clause into a class body directly, which certainly does not work. You could put it into an init
block though.
But of course it's much nicer to simply use the power of when
expression here (Which the IDE also suggests):
val finalValue = when (condition) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Undefined"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.