简体   繁体   English

Kotlin val初始化时使用

[英]Kotlin val initialization using when

Using Java I may want to initialize a final variable using a switch statement: 使用Java我可能想使用switch语句初始化最终变量:

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: 在Kotlin,尝试做同样的事情:

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. 解决方案正在使用by lazy组合,但这会创建一个新的Lazy实例。

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. 使用when作为表达式。

You can also use init block to initialize a final variable. 您还可以使用init块初始化最终变量。

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. 对我来说唯一的可能性:你直接将when子句写入类体,这当然不起作用。 You could put it into an init block though. 你可以将它放入init块中。

But of course it's much nicer to simply use the power of when expression here (Which the IDE also suggests): 但是当然when这里简单地使用表达式的强大功能要好得多(IDE也建议):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM