官术网_书友最值得收藏!

Safe call

The safe call operator is simply a question mark followed by a dot. It's important to understand that the safe cast operator will always return a value. If the left-hand side of the operator is null, then it will return null, otherwise it will return the result of the right-hand side expression:

    override fun onCreate(savedInstanceState: Bundle?) { 
         super.onCreate(savedInstanceState) 
         val locked: Boolean? = savedInstanceState?.getBoolean("locked") 
    } 

If savedInstanceState is null, then null will be returned, otherwise the result of evaluating a savedInstanceState?.getBoolean("locked") expression will be returned. Keep in mind that a nullable reference call always returns nullable, so the result of the whole expression is a nullable Boolean?. If we want to make sure we will get non-nullable Boolean, we can combine the safe call operator with the elvis operator discussed in the next section.

Multiple calls to the save call operator can be chained together to avoid a nested if expression or complex conditions like this:

    //Java idiomatic - multiple checks
    val quiz: Quiz = Quiz()
    //...
    val correct: Boolean?
 
    if(quiz.currentQuestion != null) {
        if(quiz.currentQuestion.answer != null ) {
            //do something
        }
    }
  
    //Kotlin idiomatic - multiple calls of save call operator 
    val quiz: Quiz = Quiz() 

//...
val correct = quiz.currentQuestion?.answer?.correct
// Inferred type Boolean?

The preceding chain works like this: -correct will be accessed only if the answer value is not null and answer is accessed only if the currentQuestion value is not null. As a result, the expression will return the value returned by correct property or null if any object in the safe call chain is null.

主站蜘蛛池模板: 大足县| 嘉兴市| 南和县| 民县| 华容县| 静安区| 敖汉旗| 安远县| 辽源市| 辽宁省| 上饶市| 堆龙德庆县| 邵阳市| 乡城县| 奉节县| 上饶市| 曲阜市| 永平县| 迁西县| 南投县| 新乡市| 泸溪县| 年辖:市辖区| 留坝县| 凤城市| 栾城县| 晴隆县| 乌拉特中旗| 宣化县| 嘉峪关市| 长汀县| 天峨县| 渭南市| 大冶市| 山阴县| 龙山县| 五河县| 庄浪县| 富阳市| 克什克腾旗| 信丰县|