Sealed Classes == Rust Enums

I was just sitting over here writing up a proposal to add Rust-like Enums to kotlin, when I had to look up what switch was called in kotlin, cause I knew it was different. I saw the sealed classes entry on the website and thought “I never did look into those…” Well lo and behold, they are almost exactly Rust enums!

The enums and pattern matching were the one thing I missed from Rust, and as it turns out, Kotlin has everything.

2 Likes

Kotlin has pattern matching?

No, but it does smart casting meaning you can just use the variable.

var enumVar = Status.Processing("somedata")
when(enumVar) {
    is Status.Loading -> {
        enumVar.someLoadingProp
    }
    is Status.Processing -> {
        enumVar.theData
    }
}
1 Like