在Kotlin中为具有函数链的可为空值返回默认值

给定此代码

myValue.number?.setScale(2).toString() ?: ""

I want it to return "" if number is null. But it just returns null. What concept did I not grasp here?

评论
  • Diers
    Diers 回复

    There is toString for nullable types that returns "null" if reference (or expression) is null, so in your case, ?: "" expression is unreachable. Add another null-safe call operator

    myValue.number?.setScale(2)?.toString() ?: ""