首页 > 解决方案 > Kotlin:为什么 *unresolved reference* 用于密封类的子类的构造函数参数

问题描述

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()) 
}

为什么上面的代码给出错误:未解析的引用:函数 nameOf 的名称并且对于看起来非常相似的函数stringOf可以正常工作。

标签: kotlinparametersconstructorscopesealed-class

解决方案


因为类name中没有定义任何属性Person。您拥有的所有names 都在子类中,因此nameOf父类中的函数无法访问它。


推荐阅读