简体   繁体   中英

About sealed subclass of a sealed class in Kotlin

the code below compiles while it is impossible to go through conditions Color.Dark and Color.Light as these two classes are abstract.

Did I miss something ?

sealed class Color () {
  sealed class Dark () {
    class DarkRed : Color()
    class DarkBlue : Color()
    }   
  sealed class Light {
    class LightRed : Color()
    class LightBlue : Color()
    }
}   

fun eval(c: Color) =
        when (c) {
        is Color.Dark -> println("Dark")
            is Color.Dark.DarkRed -> println("Dark Red")
            is Color.Dark.DarkBlue -> println("Dark Blue")

        is Color.Light -> println("Light")
            is Color.Light.LightRed -> println("Light Red")
            is Color.Light.LightBlue -> println("Light Blue")
}

fun main(args: Array<String>) {
    val dr = Color.Dark.DarkRed()
    eval(dr)
}

Two left indented conditions are never satisfied because Color.Dark and Color.Light do not inherit Color , and not because they are abstract. It means that 2 out of 6 is branches are useless, you can safely delete them. But other 4 branches ( is Color.Dark.DarkRed , etc.) go through all Color subclasses, and Color is a sealed class, so when can be used without else branch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM