null 값에 대한 안전성 확보
참조 변수에 객체의 ID가 저장되어 있으면 해당 객체에 접근 가능하지만 null이 저장되어 있으면 객체의 ID가 존재하지 않아 객체에 접근 불가능
null이 저장된 객체에 접근하는 코드는 NullPointerException 발생
var/val 변수명 : 자료형? = 값
var/val 변수명 : 자료형 = 값
fun testFun(str1:String?){
val value1:String = str1!!
println("$value1") // testFun(null) : 에러
}
fun testFun(str1:String?){
val value1:String = str1 ?: "기본문자열"
println("$value1") // testFun(null) : 기본문자열
}
fun testFun(t1:TestClass1?){
println("t1.str1 : ${t1?.str1}") //testFun(null) : null
println("t1.str2 : ${t1?.str2}") //testFun(null) : null
t1?.testMethod1() //testFun(null) : 실행 X
}
null을 허용하는 변수가 null 안전성을 보장(if문 사용)하는 경우 null을 허용하지 않는 타입으로 변환
fun testFun(str1:String?){
if(str1 != null){ //testFun(null) : 실행 X, 에러 X
val value1:String = str1
println("$value1")
}
}
fun testFun(str:String?) {
if(str is String){ //testFun(null) : 실행 X
println(str.length)
}
}