본문으로 바로가기

5. Using Type checks & Automatic casts

category Kotlin/Basic Syntax 2018. 5. 31. 15:57


** is operator는 expression이 해당 type의 인스턴스인지 체크한다.

** immutable local variable 또는 property가 특정 type으로 확인되면, 명시적인 캐스팅이 필요 없다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }
 
    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}
 
 
fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}
cs

 

또는,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fun getStringLength(obj: Any): Int? {
    if (obj !is Stringreturn null
 
    // `obj` is automatically cast to `String` in this branch
    return obj.length
}
 
 
fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}
cs


또는,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }
 
    return null
}
 
 
fun main(args: Array<String>) {
    fun printLength(obj: Any) {
        println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
    }
    printLength("Incomprehensibilities")
    printLength("")
    printLength(1000)
}
cs



** Kotlin은 컴파일러가 is 로 체크하는 부분을 추적하여 자동으로 캐스팅해준다.

** is 로 체크하는 구문에서는 명시적으로 캐스팅 코드를 삽입할 필요가 없다. --> Autometic Cast(Smart Cast)


가장 유용한 곳은 when expression


1
2
3
4
5
when (x) {
  is Int -> print(x)
  is String -> print(x.length)
  is IntArray -> print(x.size)
}
cs