大家好,我是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就相当实用了,起码优化了一下恶心的三目运算符。!!操作符要少用。空指针处理不是说你以后不用写类似if(XXX==null)这种判断了,而是Kotlin让所有潜在空指针异常在编译阶段就已经发现了。所以Kotlin编译出来的程序是没有无感知空指针异常的情况的,除非手贱用了!!操作符或者手动抛出空指针异常。
答:
本人答案,居然就过了,当然标准答案更加优雅。
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)
}