2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlin Koans やってみた 5

Last updated at Posted at 2025-01-12

Introduction

Nullable types

問題

Kotlin の null safety と safe calls について学び、以下の Java コードを1つの if 式のみを使って書き直してください。

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);
}

解答

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

テストはパスするけどなんだか違う気がする・・・

refactor

fun sendMessageToClient(
        client: Client?, message: String?, mailer: Mailer
) {
    val email = client?.personalInfo?.email
    if(!email.isNullOrBlank() && !message.isNullOrBlank()) mailer.sendMessage(email, message)
}

こうかな・・・?
isNullOrBlank()って知らなかった。けどサジェストされて知った☆なんかかっこいい。

koans の answer

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

素直に比較するほうがいいのかな〜・・・?

おわりに

null safety は大事よね。
思わぬところでクラッシュしてたら嫌だしね。
型に ? ついてたら、気をつけないと!!


← 前回の記事 | 次回の記事 →

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?