1
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.

madhead
  • 31,729
  • 16
  • 153
  • 201
Emile Achadde
  • 1,715
  • 3
  • 10
  • 22

1 Answers1

2

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.

madhead
  • 31,729
  • 16
  • 153
  • 201