What is difference between "as" and "is" operator in Kotlin?
Asked Answered
B

10

28

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?

Burma answered 2/11, 2017 at 3:50 Comment(0)
M
45

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`
}
Moolah answered 2/11, 2017 at 4:1 Comment(0)
G
43

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()
Guadiana answered 2/11, 2017 at 4:12 Comment(6)
so if i always use 'is', that mean I can never use 'as' right? because IDE has smart castBurma
@ShawnPlus It depends on your use case. as? is better if you use the variable in multiple place. Smart cast only work within the bracket only.Guadiana
can I see the any evidence reference of as is not recommended?Flita
@Guadiana smart cast works outside bracket, if inside bracket returns. Eg: if(a !is String) return //after this line, a is smart casted to stringRouse
@Flita ClassA as ClassB will throw exception if cast is not possible. However ClassA as? ClassB will return null if cast is not possibleMistake
I think there are also some other case where as? is used vs is. Consider if I have a function that returns something requireActivity(). With if (requireActivity() is MainActivity) { requireActivity().doSomething() } is not valid (unable to smartcast) since it is a function call instead of property, in this case requireActivity as? MainActivity be come handy, since I can do (requireActivity as? MainActivity)?.let { it.doSomething() }Unlace
K
16

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

enter image description here

Kaitlin answered 18/12, 2018 at 19:34 Comment(0)
T
3

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

Top answered 7/1, 2020 at 9:40 Comment(0)
A
1

As per Kotline official documents

  1. Usually, the cast operator throws an exception if the cast is not possible. Thus, we call it unsafe. The unsafe cast in Kotlin is done by the infix operator as

    val x: String = y as String
    

Note that null cannot be cast to String as this type is not nullable, i.e. if y is null, the code above throws an exception. In order to match Java cast semantics we have to have nullable type at cast right hand side, like:

    val x: String? = y as String?

So here use is instead of as

 fun cast(a: A) {
    if (a is Person) {
        val p = a as Person
    }
}
Apple answered 2/11, 2017 at 4:7 Comment(1)
we can use 'if' Statement to avoid ClassCastException, why need 'as'? , I can always use 'if' and 'is'Burma
M
1

as is used for explicit type casting

val p = a as Person;

is is exactly the same as instanceof in Java. Which is used to check if an object is an instance of a class

if(a  is  Person)  {
      // a is an instance of Person
}

You can also used !is as is it not an object of a class

fun cast(a: A)  {
    if(a  is  Person)  {
        val p = a as Person;
    }
}
Measly answered 2/11, 2017 at 4:48 Comment(0)
P
1

is Operator is checking datatype

but as is for casting to some type for example casting Int to String

Predator answered 16/7, 2019 at 19:44 Comment(0)
B
0

so

if(a is Person){
    a as Person
}else{
    null
}  

equivalent

a as? Person

Is this answer?

Burma answered 2/11, 2017 at 6:2 Comment(0)
C
0

you can use is operator

fun cast(a:A){
    if (a is Person){
       var person = a
    }
}
Census answered 16/7, 2018 at 8:35 Comment(1)
Please edit your answer and add explanation to your code.Perquisite
H
0

is checks that a value has a certain type. is used in when expressions for the same purpose.

as is used for type casts. specifies an alias for an import.`

fun cast(a: A) {
if (a is Person) {
    val p = a as Person
} }
Hydraulic answered 29/12, 2023 at 13:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.