【问题标题】:Idiomatic way to assign value if not null如果不为空,则分配值的惯用方式
【发布时间】:2021-03-26 23:39:53
【问题描述】:

我想实现这个:

val foo = if (getNullableValue() != null) getNullableValue() else computeDefaultValue()

我不喜欢的是getNullableValue() 的重复。试图摆脱重复我想出了这个:

val foo = getNullableValue()?.also{}?: run { computeDefaultValue() }

不确定这是否被认为是惯用的。 IDE 会警告 also 的空主体。有没有更好的方法来实现这一点?

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    这就是猫王接线员的用途:

    val foo  = getNullableValue() ?: computeDefaultValue()
    

    例如:

    fun getNullableValue1(): Int? {
        return null
    }
    
    fun getNullableValue2(): Int? {
        return 22
    }
    
    fun computeDefaultValue(): Int {
        return 44
    }
    
    println(getNullableValue1() ?: computeDefaultValue())
    println(getNullableValue2() ?: computeDefaultValue())
    

    结果:

    44
    22
    

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 2012-08-31
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多