Emile Achadde
Emile Achadde

Reputation: 1815

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 ?

Upvotes: 0

Views: 183

Answers (2)

Kiryl Tkach
Kiryl Tkach

Reputation: 3644

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.

Upvotes: 1

RobCo
RobCo

Reputation: 6515

Because 'DarkRed' is both Dark and DarkRed, and is Dark is checked before is DarkRed.

when will enter the first clause that resolves to true.

To fix this put the most specific checks before the lesser specific checks.

Upvotes: 3

Related Questions