【发布时间】: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