- Android Development with Kotlin
- Marcin Moskala Igor Wojda
- 260字
- 2021-07-02 18:48:34
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.
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- Java入門(mén)經(jīng)典(第6版)
- Python Geospatial Development(Second Edition)
- Java:Data Science Made Easy
- 精通Scrapy網(wǎng)絡(luò)爬蟲(chóng)
- YARN Essentials
- PLC編程與調(diào)試技術(shù)(松下系列)
- Java 9模塊化開(kāi)發(fā):核心原則與實(shí)踐
- SQL Server 2016數(shù)據(jù)庫(kù)應(yīng)用與開(kāi)發(fā)
- Python極簡(jiǎn)講義:一本書(shū)入門(mén)數(shù)據(jù)分析與機(jī)器學(xué)習(xí)
- Test-Driven Development with Django
- H5+移動(dòng)營(yíng)銷(xiāo)設(shè)計(jì)寶典
- Clojure High Performance Programming(Second Edition)
- Hadoop Blueprints
- Distributed Computing with Python