I completely missed this Kotlin superior characteristic in my earlier publish – Full C# to Kotlin Syntax Comparisons.
I got here to concentrate on this sensible solid solely after 8 months of Kotlin growth, and I may need been utilizing it with out figuring out it. The Android Studio IDE takes care of it!
As an instance you have got 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 specific solid under.
val childObj = obj as ChildClass
childObj.worth
However the Kotlin compiler can sensible solid mechanically for you within the following state of affairs:
Instance 1
enjoyable smartCastExample1() {
val obj: BaseClass = ChildClass(worth = 7)
if (obj is ChildClass) {
println("Baby worth is ${obj.worth}")
val childObj = obj as ChildClass
println("Baby worth is ${childObj.worth}")
}
}
obj
on thisif
scope have to beChildClass
, thus Kotlin compiler sensible casts it
Instance 2
enjoyable smartCastExample2() {
val obj: BaseClass = ChildClass(worth = 7)
if (obj !is ChildClass) return
println("Baby worth is ${obj.worth}")
}
obj
right here have to beChildClass
because it has been returned if it isn’t.
Instance 3
enjoyable smartCastExample3()
This
obj.worth
solely will get evaluated whenobj
isChildClass
. For those who changeobj !is ChildClass
toobj is ChildClass
, the sensible solid will not work.
Instance 4
enjoyable smartCastExample3() {
val obj: BaseClass = ChildClass(worth = 7)
if (obj is ChildClass && obj.worth == 7) return
}
Just like instance above, the second verify is simply evaluated when
obj
isChildClass
. For those who changeobj is ChildClass
toobj !is ChildClass
, the sensible solid will not work.
The instance right here is solid from tremendous kind to subtype. It additionally works for nullable kind to non-nullable kind. See extra instance right here.