Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin val initialization using when

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?

like image 274
LppEdd Avatar asked Jan 15 '18 10:01

LppEdd


1 Answers

How about this construction:


    val finalValue: String = when (condition) {
        1 -> "One"
        2 -> "Two"
        3 -> "Three"
        else -> "Undefined"
    }

Using when as an expression.

like image 102
azizbekian Avatar answered Nov 11 '22 00:11

azizbekian