컴퓨터 언어/코틀린

[Kotiln] 코틀린 nullable 변수 처리

훈츠 2020. 2. 18. 17:56
반응형

안녕하세요. 훈츠 입니다. 금일은 nullable 변수에 대한 처리에 대해 알아보도록 하겠습니다. 

Nullable 연산자 종류 [ ?. null safe , ?: 엘비스 , !! null 어소션]

  • ?.  null safe 연산자 (마치 if 문 처럼 동작합니다.) 스코프 함수와 같이 사용하면 편리합니다.
  • ?:  엘비스 연산자 null이면 대체 되어서 동작 합니다. 
  • !!. 논 null 어소션 연산자 (일부러 null값이 오면 익셉션 에러를 발생 시킵니다.) 
val a : String? = "test"

a?.run {println(a)} // null safe 연산자 
a?:println("null입니다.") // 엘비스 연산자
println(a!!.toUpperCase()) // null 어소션 연산자
//출력화면
test
TEST

//두번째 경우의 수 
val a : String? = null

a?.run {println(a)} // null safe 연산자 
a?:println("null입니다.") // 엘비스 연산자
println(a!!.toUpperCase()) // null 어소션 연산자
//출력화면
null입니다.
Exception in thread "main" kotlin.KotlinNullPointerException
at com.rainfactory.mykotilnplayground.ArrayKt.main(Array.kt:14)
at com.rainfactory.mykotilnplayground.ArrayKt.main(Array.kt)

 객체의 동일성과 내용의 동일성 

  • 객체의 동일성 : a === b , 내용의 동일성 : a == b
  • 코틀린은 Any라는 최상위 클래스를 상속받아 내부적으로 equals()함수가 반환하는 boolean값으로 판단한다. 
  • 기본 자료형에는 이미 구현되어 있지만, 내가 직접 만들때는 아래와 같이 구문을 만들어 줘야 한다. 
fun main() {
    var a = Product("콜라",1000)
    var b = Product("콜라",1000)
    var c = a
    var d = Product("사이다",1000)

    println( a == b)
    println( a === b)

    println( a == c)
    println( a === c)

    println( a == d)
    println( a === d)
}

class Product (val name: String, val price: Int){
    override fun equals(other: Any?): Boolean {
        if(other is Product){
            return other.name == name && other.price == price
        } else {
            return false
        }
    }
}

//출력화면
true
false
true
true
false
false
반응형