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正常工作。
因为name
在Person
类中没有定义属性。name
您拥有的所有子类都在子类中,因此nameOf
父类中的函数无法访问它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句