Hanbit the Developer

Kotlin Documentation | Null safety 본문

Mobile/Kotlin

Kotlin Documentation | Null safety

hanbikan 2023. 5. 22. 14:24

Kotlin Documentation

Category: Concepts

문서 링크: https://kotlinlang.org/docs/null-safety.html


Java에서 NPE 문제가 가장 많이 일어나는 문제 중 하나이다.

Kotlin에서는 다음의 경우 NPE가 발생한다.

  • throw NullPointerException()
  • !!의 부적절한 사용
  • constructor에서 초기화되지 않은 this를 사용한 경우

Elvis operator

?:를 통한 null 처리:

fun foo(node: Node): String? {
    val parent = node.getParent() ?: return null
    val name = node.getName() ?: throw IllegalArgumentException("name expected")
    // ...
}

The !! operator

값을 non-null로 변환하며, 만약 값이 null이었다면 NPE를 던진다.

Safe casts

캐스팅이 성공적이지 않으면 null을 반환한다.

val aInt: Int? = a as? Int