LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第6回:Nullable types

Last updated at Posted at 2022-03-10

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Nullable types

KotlinのNULLセーフティとセーフコールについて学び、以下の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
) {
    TODO()
}

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

問題のポイント

Kotlinではnullを許容する型としない型が存在します。

  // nullを許容しない型宣言(Non-Null)
  var non_null: String = ""

  // nullを許容する型宣言(Nullable)
  var nullable: String? = null

nullableな変数にアクセスする場合、?つなぎでアクセスします。?なしではコンパイルエラーになります。
JavaではNullPointerExceptionを人力で防いでいたのをKotlinではコンパイラーが教えてくれる感じですね。
実行時にnullでない時に、?つなぎの右側がそのまま実行され、nullの時は何もしない動作になります。

val length = nullable?.length

解答例

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

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

だんだん記述量が多くなるにつれて、コード補完してくれないブラウザ上でコードを書くのがつらくなってきました😅

0
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
0
0