简体   繁体   中英

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.

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

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