I do not know Kotlin can do sensible forged like this. It’s sensible sufficient to forged it for you routinely, so that you need not explicitly forged anymore.
This text was initially revealed at vtsen.hashnode.dev on Might 21, 2022.
I completely missed this Kotlin superior function in my earlier publish – Full C# to Kotlin Syntax Comparisons.
I got here to pay attention to this sensible forged solely after 8 months of Kotlin improvement, and I might need been utilizing it with out realizing it. The Android Studio IDE takes care of it!
To illustrate you’ve gotten BaseClass and ChildClass like this.
open class BaseClass
class ChildClass(val worth: Int): BaseClass()
and, you create the ChildClass object and being referenced by the BaseClass
val obj: BaseClass = ChildClass(worth = 7)
To entry the info in ChildClass, you do express forged beneath.
val childObj = obj as ChildClass
childObj.worth
However the Kotlin compiler can sensible forged routinely for you within the following situation:
Instance 1
enjoyable smartCastExample1() {
val obj: BaseClass = ChildClass(worth = 7)
//Calling obj.worth right here isn't allowed
//as a result of obj belongs to BaseClass
if (obj is ChildClass) {
//obj on this scope is wise forged to ChildClass.
//Thus, accessing the obj.worth is allowed right here
println("Little one worth is ${obj.worth}")
//You need not express forged like this
val childObj = obj as ChildClass
println("Little one worth is ${childObj.worth}")
}
}
objon thisifscope should beChildClass, thus Kotlin compiler sensible casts it
Instance 2
enjoyable smartCastExample2() {
val obj: BaseClass = ChildClass(worth = 7)
if (obj !is ChildClass) return
// obj is wise forged to ChildClass
println("Little one worth is ${obj.worth}")
}
objright here should beChildClassbecause it has been returned if it isn’t.
Instance 3
enjoyable smartCastExample3() obj.worth == 7) return
This
obj.worthsolely will get evaluated whenobjisChildClass. If you happen to changeobj !is ChildClasstoobj is ChildClass, the sensible forged will not work.
Instance 4
enjoyable smartCastExample3() {
val obj: BaseClass = ChildClass(worth = 7)
// obj at proper aspect of && is wise forged to ChildClass
if (obj is ChildClass && obj.worth == 7) return
}
Much like instance above, the second test is just evaluated when
objisChildClass. If you happen to changeobj is ChildClasstoobj !is ChildClass, the sensible forged will not work.
The instance right here is forged from tremendous sort to subtype. It additionally works for nullable sort to non-nullable sort. See extra instance right here.

