nullable type : null을 가질 수 있는 type (type 뒤에 물음표) ex) var str: String? = "AAA" str=null // str은 nullable type으로 null을 가질 수 있다. println(${str.length}) // nullable 타입은 null이 가능하므로 참조하는 것이 위험하다.=> str이 null일 때 Error가 난다. nullable type의 참조의 방법 ex) println(${str?.length}) // save call을 하는 방법 , str이 null이면 null 출력. println(${str!!.length}) // 느낌표 2개를 붙이면 str이 null 이라도 참조/호출 . str이 null인 경우 null pointer exception 발생 println(${str?.length ?: "null이면 여기 출력됨"}) // elvis operator와 함께 사용할 수 있다. non-null type : null을 가질 수 없는 typeex) var str : String = "AAA" str=null // -> str은 non-null type이라 null을 가질 수 없다. 따라서 Error
'Kotlin' 카테고리의 다른 글
[Kotlin] Any 클래스, 타입 체크 (3) | 2018.07.18 |
---|---|
[Kotlin] 기본 자료형, 변수와 상수 (0) | 2018.07.18 |