{Kotlin學習日記}Day24 Koan第八關

大家好,我是William。今天是Koan第八關,Nullable types,空指針類型。

闖關鏈接:
https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Nullable%20types/Task.kt

Introduction

Nullable types

Read about null safety and safe calls in Kotlin and rewrite the following Java code using only one if expression:

public void sendMessageToClient( 
    @Nullable Client client, 
    @Nullable String message,
    @NotNull Mailer mailer
) {
    if (client == null || message == null) return;

    PersonalInfo personalInfo = client.getPersonalInfo(); 
    if (personalInfo == null) return; 

    String email = personalInfo.getEmail(); 
    if (email == null) return; 

    mailer.sendMessage(email, message);
}

解:
空指針處理是Kotlin一大特色,這里就不展開說了,直接看題目的超鏈接,先了解一下。個人覺得Safe Call作用不大,但是Elvis Operator就相當實用了,起碼優(yōu)化了一下惡心的三目運算符。!!操作符要少用??罩羔樚幚聿皇钦f你以后不用寫類似if(XXX==null)這種判斷了,而是Kotlin讓所有潛在空指針異常在編譯階段就已經發(fā)現(xiàn)了。所以Kotlin編譯出來的程序是沒有無感知空指針異常的情況的,除非手賤用了!!操作符或者手動拋出空指針異常。

答:
本人答案,居然就過了,當然標準答案更加優(yōu)雅。

fun sendMessageToClient(
    client: Client?, message: String?, mailer: Mailer
){
    if(client==null||message==null) return
    
    val personalInfo:PersonalInfo? = client?.personalInfo
    if(personalInfo==null) return
    
    val email = personalInfo?.email
    if(email==null) return
    
    mailer.sendMessage(email, message)
}

class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
    fun sendMessage(email: String, message: String)
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容