https://kotlinlang.org logo
#android
Title
# android
c

chanjungskim

03/20/2023, 8:36 AM
Can you tell the differences between 1. sealed interface vs sealed class 2. sealed interface vs interface And with examples?
j

Javier

03/20/2023, 8:52 AM
classes can have state and interfaces can’t. a sealed interface is closed in terms of you will know with pattern matching what are the implementations that exist. With a normal interface you can’t
c

chanjungskim

03/20/2023, 9:09 AM
what is pattern matching?
t

Tom Hermann

03/21/2023, 12:17 AM
An interface defines a contract that a class can implement. Here is an example from the java website converted to Kotlin:
Copy code
package com.example

interface Bicycle {
    fun changeCadence(newValue: Int)
    fun changeGear(newValue: Int)
    fun speedUp(increment: Int)
    fun applyBrakes(decrement: Int)
}
Note that this interface simply defines what you can generally do with a bicycle, not how it is accomplished. Classes can implement interfaces, so if you wanted to model a Peloton for example, you could start like this:
Copy code
package com.example

class Peloton : Bicycle {
    override fun changeCadence(newValue: Int) {
        // perform change cadence
    }

    override fun changeGear(newValue: Int) {
        // perform change gear
    }

    override fun speedUp(increment: Int) {
        // perform speed up
    }

    override fun applyBrakes(decrement: Int) {
        // perform slow down
    }
}
In this example a Peloton is-a bicycle, since it implements the bicycle interface, so anywhere that wants a "bicycle" will accept a Peloton. So lets say you have a "Rider" that can ride any old bicycle. Here is an example of creating a rider instance and having them ride a peloton.
Copy code
package com.example

class Rider {
    fun ride(bicycle: Bicycle) {
        bicycle.changeGear(1)
        bicycle.speedUp(11)
    }
}

fun main() {
    val peloton = Peloton()
    Rider().ride(peloton)
}
So you can see that you could swap out different bike implementations (imagine a
MountainBike
,
BmxBike
, etc.) and as long as it conforms to the contract you can have the rider ride it. Once you fully understand classes / interfaces, Kotlin's site has a great write-up on
sealed
interfaces and classes: https://kotlinlang.org/docs/sealed-classes.html
10 Views