DEV Community

sunj
sunj

Posted on

Kotlin Nullable/ NonNull, 2024-03-18

fun nullcheck(){
   var name = "example"
   var nullName = String? = null

   var nameInUpperCase = name.toUpperCase()
   var nullNameInUpperCase = nullName?.toUpperCase()
}
Enter fullscreen mode Exit fullscreen mode

null이 가능하려면 타입뒤에 ? 을 붙여야 한다. 없으면 기본적으로 noNull
두 번째 경우, null이면 nullNameInUpperCase = null
null이 아니면 toUpperCase()를 처리한다

val lastName : String? = null
val fullName = name +" "+ (lastName?: "NO LastName")
println(fullName)

Enter fullscreen mode Exit fullscreen mode

null일 때 NO LastName 출력
아닐 때 정한 String 값 출력

fun ignoreNulls(str : String?){
   val mNotNull : String = str!!
   val upper = mNotNull.toUpperCase()

   val email : String? = "emxample@example.com" 
   //email이 null이 아닐 경우
   email?.let{
       println("My email is ${email}")
   }
}
Enter fullscreen mode Exit fullscreen mode

!!는 절대 null타입이 아님을 명시 해줌

참조 : 유투브 강의 Code with Joyce

Top comments (0)