chernyshevdev
chernyshevdev

Reputation: 31

Kotlin "is" operator for objects in when expression

Lets imagine we have sealed class with data classes and objects inside:

    sealed class CarEvent {
         data class FilledFuel(val fuelAmount: Float) : CarEvent()
         data class ChangedPart(val part: CarPart) : CarEvent()
         object StartedEngine : CarEvent()
         }

Then we have when statement reducing events:

when(event) {
is CarEvent.FilledFuel -> { do something }
is CarEvent.ChangedPart -> { do something }
CarEvent.StartedEngine -> { do something }
}

The questing is: what is the most true approach for StartedEngine object: compare it using is operator, or without is operator (using default == inside when statement). Is there any difference between these two?

Upvotes: 3

Views: 1197

Answers (2)

Amin
Amin

Reputation: 3186

When has a syntatic sugar of evaluating what's inside parentheses versus each case When you put nothing, it checks for equality and in other cases it checks what you put there

In case of objects, kotlin creates a class for them and creates a singleton INSTANCE and if you try to look at it from a Java point of view, when you put is StartedEngine it's like checking event instanceof StartedEngine and when put StratedEngine it's like event.equals(StartedEngine.INSTANCE) so one of them check for type while the other checks for equality

On the other hand, object are strictly singletons which you cannot inherit, or override anything from them so it doesn't matter if you check for equality or is unless you've override equals in that object.

So they're not different in usage, nor in action. They are just different approaches.

sealed class A{
    abstract val name:String
    object AAA : A(){
        override val name get()= "AA"
        override fun equals(o: Any?) : Boolean {
            println("AAA equality call")
            return super.equals(o)
            }
    }
    object BBB : A() {
        override val name get()="BB"
    }
}
fun main() {
    val o : A = A.AAA
    
    when(o){
        is A.AAA -> println("o is AAA")
    }
    when(o){
        A.AAA -> println("o==AAA")
    }
}

But notice that if the override fun equals in AAA returned false, o==AAA wouldn't get printed also note that in second when, equals gets called and it prints AAA equality call

Output

o is AAA
AAA equality call
o==AAA

Upvotes: 3

a_local_nobody
a_local_nobody

Reputation: 8191

Is there any difference between these two?

Yes, is checks if something is an instance of a specific type, where as == will check if one object is the same as another

As an example:

 val foo = 5

 val result = foo is Int

This will always be true, because foo is a type of integer.

but if you consider

 val foo = 5

 val result = foo == 7

This will return false, correctly, because these two values aren't the same thing.

In your case, I don't think it would matter, but is would probably make more sense

Upvotes: 3

Related Questions