Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between "as" and "is" operator in Kotlin?

Tags:

casting

kotlin

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?

like image 682
Shawn Plus Avatar asked Nov 02 '17 03:11

Shawn Plus


People also ask

What is is VS as in Kotlin?

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) .

What does is do in Kotlin?

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.

What is == and === in Kotlin?

In Kotlin there are two types of equality: Structural equality ( == - a check for equals() ) Referential equality ( === - two references point to the same object)

Is not operator Kotlin?

The NOT Operator: ! The logical NOT operator ( ! ) evaluates the value of a Boolean expression and then returns its negated value.


4 Answers

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`
}
like image 171
Grzegorz Piwowarek Avatar answered Oct 17 '22 18:10

Grzegorz Piwowarek


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()
like image 35
Joshua Avatar answered Oct 17 '22 16:10

Joshua


"Kotlin in action" by Dmitry Jemerov and Svetlana Isakova has a good example of as and is:

enter image description here

like image 14
JC Wang Avatar answered Oct 17 '22 17:10

JC Wang


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

like image 3
Arun Yogeshwaran Avatar answered Oct 17 '22 18:10

Arun Yogeshwaran