Kotlin val初始化使用when [英] Kotlin val initialization using when

查看:109
本文介绍了Kotlin val初始化使用when的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java,我可能想使用switch语句初始化最终变量:

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"
}

导致编译错误.
解决方案使用的是by lazy组合,但这会创建一个新的Lazy实例.

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?

推荐答案

这种结构如何:



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

使用 when 作为表达式.

Using when as an expression.

这篇关于Kotlin val初始化使用when的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆