In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

前端 未结 2 471
孤独总比滥情好
孤独总比滥情好 2020-11-22 12:42

If I have a nullable type Xyz?, I want to reference it or convert it to a non-nullable type Xyz. What is the idiomatic way of doing so in Kotlin?<

2条回答
  •  执笔经年
    2020-11-22 13:31

    The previous answer is a hard act to follow, but here's one quick and easy way:

    val something: Xyz = createPossiblyNullXyz() ?: throw RuntimeError("no it shouldn't be null")
    something.foo() 
    

    If it really is never null, the exception won't happen, but if it ever is you'll see what went wrong.

提交回复
热议问题