Language/kotlin

널 가능성

세모데 2020. 1. 9. 11:39

코틀린은 기본적으로 NPE ( null point exception )를 방지하기 위해 변수에 null 값을 허용하지 않습니다.

null를 사용하기 위해서는 아래와 같이 사용합니다.

 

1. 기본 규칙

   type    : type과 같은 타입만 허용, null 사용불가

   type?  : type 또는 null

 

   type?. : type에 관련된 함수 호출시 null일 경우 다른 결과 return

     String str

     str?.get(str.length - 1) ?: "".single()    // str이 null 이면 "" 반환

 

  type?.let : type이 null 이면 해당 구문이 실행되지 않음

     String str

     str?.let { println(str) }   // str이 null 아닐때 println 실행

   

 

2. 사용 예제

null를 허용한 후, null 체크를 하지 않고 compile를 하면 에러가 발생함

 

아래 처럼 null 체크를 해야 함.

fun testnull( str : String?) : Int {

     if ( str != null ) {

           return str.length

     } 

 

    return 0

}