大家好笙各,我是William唱蒸。今天是Koan第八關(guān)邦鲫,Nullable types灸叼,空指針類(lèi)型神汹。
闖關(guān)鏈接:
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一大特色庆捺,這里就不展開(kāi)說(shuō)了,直接看題目的超鏈接屁魏,先了解一下滔以。個(gè)人覺(jué)得Safe Call作用不大,但是Elvis Operator就相當(dāng)實(shí)用了氓拼,起碼優(yōu)化了一下惡心的三目運(yùn)算符你画。!!操作符要少用√已空指針處理不是說(shuō)你以后不用寫(xiě)類(lèi)似if(XXX==null)這種判斷了坏匪,而是Kotlin讓所有潛在空指針異常在編譯階段就已經(jīng)發(fā)現(xiàn)了。所以Kotlin編譯出來(lái)的程序是沒(méi)有無(wú)感知空指針異常的情況的撬统,除非手賤用了!!操作符或者手動(dòng)拋出空指針異常适滓。
答:
本人答案,居然就過(guò)了恋追,當(dāng)然標(biāo)準(zhǔn)答案更加優(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)
}