https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jukka Siivonen

04/01/2022, 9:29 AM
Noob question about sealed classes usage, what am I missing here
image.png
t

thanksforallthefish

04/01/2022, 9:31 AM
it should be
object Bar2 : Reason()
j

Jukka Siivonen

04/01/2022, 9:32 AM
but then its not sub-type BarReason right?
r

Rob Elliot

04/01/2022, 9:34 AM
Nested
object
isn't a subtype of the thing it's nested in.
Bar1
has type
BarReason.Bar1
, which is not a subtype of
BarReason
.
t

thanksforallthefish

04/01/2022, 9:34 AM
it is not a sub class of BarReason in your example though, is it?
val reason: BarReason = BarReason.Bar1
fails righ?
sniped 😄
😁 1
j

Jukka Siivonen

04/01/2022, 9:36 AM
Yeah that is correct
v

Vampire

04/01/2022, 9:41 AM
So make it
object Bar2 : BarReason()
j

Jukka Siivonen

04/01/2022, 9:45 AM
Yeah I think I got it
Copy code
sealed class Reason
sealed class FooReason: Reason()
sealed class BarReason: Reason()

object Bar1: BarReason()

fun reason(reason: Reason) {
    when (reason) {
        is FooReason -> println("Foo reason" + reason)
        is BarReason -> println("Bar reason" + reason)
    }
}

class ReasonTest {
    fun test() {
        reason(Bar1)
    }
}
and when is exhaustive
👍 1
5 Views