Search code examples
kotlincompanion-object

Kotlin companion object unexpected result


sealed class Color () {
    sealed class Dark (): Color() {
    object DarkRed : Dark()
    object DarkBlue : Dark()
    }   
    override fun toString(): String = when (this) {
        is Color.Dark -> "Dark"
        is Color.Dark.DarkRed -> "Dark Red"
        is Color.Dark.DarkBlue -> "Dark Blue"
    }
    companion object Companion {
    fun make(name: String): Color = when (name) {
        "DarkRed" -> Color.Dark.DarkRed 
        "DarkBlue" -> Color.Dark.DarkBlue
        else -> throw Exception ("Error unkown color '$name'") 
    }
    }
}
fun main(args: Array<String>) {
    val color = Color.Companion.make("DarkRed")
    println (color.toString()) // Dark is printed not "Dark Red"
}

The code above prints Dark while I expected Dark Red. It seems that the make returned type Color.Dark.DarkRed is interpreted as Color.Dark by the ofString() function, why ?


Solution

  • You can just put line is Color.Dark -> "Dark" in the end of toString function. In your case is Color.Dark returns true for DarkRed.