【问题标题】:Kotlin : Why *unresolved reference* for a constructor parameter of a subclass of a sealed classKotlin:为什么 *unresolved reference* 用于密封类的子类的构造函数参数
【发布时间】:2020-02-29 15:54:19
【问题描述】:
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 提供 error: unresolved reference: name 并为看起来非常相似的函数 stringOf 正常工作。

【问题讨论】:

  • 因为它没有智能转换为实际具有name 的实际类型。为什么不把它移到Person
  • @EpicPandaForce 我要获取数据类的name构造函数,密封类没有构造函数。

标签: kotlin parameters constructor scope sealed-class


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多