In Java, I can write code like:
void cast(A a) {
if(a instanceof Person) {
Person p = (Person) a;
}
}
In Kotlin, what should I do?
Use as
operator or is
operator?
Type check is a way of checking the type( DataType ) or Class of a particular instance or variable while runtime to separate the flow for different objects. In few languages, it's also denoted as Run Time Type Identification (RTTI) .
In Kotlin, the "===" operator checks the referential equality of two objects. Any expression "a===b" will evaluate to True if and only if both "a" and "b" point to the same object. That is, both "a" and "b" share the same address.
In Kotlin there are two types of equality: Structural equality ( == - a check for equals() ) Referential equality ( === - two references point to the same object)
The NOT Operator: ! The logical NOT operator ( ! ) evaluates the value of a Boolean expression and then returns its negated value.
is X
is the equivalent of instanceof X
foo as X
is the equivalent of ((X) foo)
Additionally, Kotlin performs smart casting where possible, so no additional cast needed after you check the type using is
:
open class Person : A() {
val foo: Int = 42
}
open class A
and then:
if (p is Person) {
println(p.foo) // look, no cast needed to access `foo`
}
is
is type checking. But Kotlin has smart cast which means you can use a
like Person
after type check.
if(a is Person) {
// a is now treated as Person
}
as
is type casting. However, as
is not recommended because it does not guarantee run-time safety. (You may pass a wrong object which cannot be detected at compiled time.)
Kotlin has a safe cast as?
. If it cannot be casted, it will return null instead.
val p = a as? Person
p?.foo()
"Kotlin in action" by Dmitry Jemerov and Svetlana Isakova has a good example of as
and is
:
is - To check if an object is of a certain type
Example:
if (obj is String) {
print(obj.length)
}
as - To cast an object to a potential parent type
Example:
val x: String = y as String
val x: String? = y as String?
val x: String? = y as? String
Reference: https://kotlinlang.org/docs/reference/typecasts.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With