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

More than 3 years have passed since last update.

【Kotlin】サンプルコードから学ぶnull安全

0
Last updated at Posted at 2023-04-11

KotlinとJavaのサンプルコードからnull安全について学ぶ

Java

public class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = null;
        String name = person.getName(); // NullPointerExceptionが発生
        System.out.println("Name: " + name);
    }
}
  1. Personクラスのインスタンスをnullで初期化
  2. getName()メソッドを呼び出して、その戻り値をname変数に代入

nullのオブジェクトに対してメソッドを呼び出したため、NullPointerExceptionが発生

Kotlin

Kotlin
class Person(val name: String)

fun main() {
    val person: Person? = null
    val name = person?.name
    println("Name: $name")
}
  1. null許容型(?)を使用して、Personクラスのインスタンスをnullで初期化
  2. セーフコール演算子(?.)を使用して、person変数がnullでない場合にnameプロパティにアクセスし、その値をname変数に代入

null許容型とセーフコール演算子を使用することで、nullに対するエラーを回避することができる

また、エルビス演算子(?:)を使用することで、nullの場合に代替値を設定することができる

class Person(val name: String)

fun main() {
    val person: Person? = null
    val name = person?.name ?: "No name"
    println("Name: $name")
}

person変数がnullの場合、name変数には「No name」という文字列が代入される

参考文献

Kotlin Docs | Kotlin Documentation

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?