Search code examples
kotlinparametersconstructorscopesealed-class

Kotlin : Why *unresolved reference* for a constructor parameter of a subclass of a sealed class


sealed class Person () {
    data class Man (val name: String): Person()
    data class Woman (val name: String): Person() 

    fun stringOf(): String {
    return when (this) {
        is Person.Man -> "Mr "+this.name
        is Person.Woman -> "Mrs "+this.name
    }
    } // works fine

    fun nameOf() : String {
        return this.name // error: unresolved reference: name
    }
}

fun main(args: Array<String>) {
    val man = Person.Man("John Smith")
    println (man.stringOf()) 
}

Why the code above gives error: unresolved reference: name for the function nameOf and works correctly for function stringOf which looks very similar.


Solution

  • Because no name property is defined in Person class. All names you have are in subclasses, so nameOf function in the parent class cannot access it.