Kotlin 스마트 캐스트는 굉장합니다!
이 기사는 원래 2022년 5월 21일 vtsen.hashnode.dev에 게시되었습니다.
이전 게시물Complete C# to Kotlin Syntax Comparisons에서 이 Kotlin 멋진 기능을 완전히 놓쳤습니다.
코틀린 개발 8개월이 지나서야 이 스마트 캐스트를 알게 되었고, 나도 모르게 사용하고 있었을지도 모릅니다. Android Studio IDE가 처리합니다!
이와 같은
BaseClass 및 ChildClass가 있다고 가정해 봅시다.open class BaseClass
class ChildClass(val value: Int): BaseClass()
ChildClass 개체를 만들고 BaseClass에서 참조하는val obj: BaseClass = ChildClass(value = 7)
ChildClass 의 데이터에 액세스하려면 아래에서 명시적 캐스트를 수행합니다.val childObj = obj as ChildClass
childObj.value
그러나 Kotlin 컴파일러는 다음 시나리오에서 자동으로 스마트 캐스팅할 수 있습니다.
예 1
fun smartCastExample1() {
val obj: BaseClass = ChildClass(value = 7)
//Calling obj.value here is not allowed
//because obj belongs to BaseClass
if (obj is ChildClass) {
//obj in this scope is smart cast to ChildClass.
//Thus, accessing the obj.value is allowed here
println("Child value is ${obj.value}")
//You don't need to explicit cast like this
val childObj = obj as ChildClass
println("Child value is ${childObj.value}")
}
}
objin thisifscope must beChildClass, thus Kotlin compiler smart casts it
예 2
fun smartCastExample2() {
val obj: BaseClass = ChildClass(value = 7)
if (obj !is ChildClass) return
// obj is smart cast to ChildClass
println("Child value is ${obj.value}")
}
objhere must beChildClasssince it has been returned if it is not.
예 3
fun smartCastExample3() {
val obj: BaseClass = ChildClass(value = 7)
// obj at right side of || is smart cast to ChildClass
if (obj !is ChildClass || obj.value == 7) return
}
This
obj.valueonly gets evaluated whenobjisChildClass. If you changeobj !is ChildClasstoobj is ChildClass, the smart cast won't work.
예 4
fun smartCastExample3() {
val obj: BaseClass = ChildClass(value = 7)
// obj at right side of && is smart cast to ChildClass
if (obj is ChildClass && obj.value == 7) return
}
Similar to example above, the second check is only evaluated when
objisChildClass. If you changeobj is ChildClasstoobj !is ChildClass, the smart cast won't work.
여기의 예는 상위 유형에서 하위 유형으로 캐스트됩니다. nullable 유형에서 nullable이 아닌 유형에 대해서도 작동합니다. 더 많은 예here를 참조하십시오.
또한보십시오
Reference
이 문제에 관하여(Kotlin 스마트 캐스트는 굉장합니다!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/vtsen/kotlin-smart-cast-is-awesome-3d6n텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)