kotlin - 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可以正常工作。
解决方案
因为类name
中没有定义任何属性Person
。您拥有的所有name
s 都在子类中,因此nameOf
父类中的函数无法访问它。
推荐阅读
- android - 如何等待 ListAdapter.submitList() 执行并调用 RecyclerView.smoothScrollToPosition(0);
- r - 如何将参数传递给 plot.surface() [R fields package] 内部的 contour()
- php - 在 bluehost 上为 mysql 设置远程访问
- python - 模板从日期起休息一天
- jupyter-notebook - 如何从 Jupyter 中更改 Jupyter 内核和 conda 环境?
- php - 当存在某些查询字符串时定义 Laravel 路由
- r - 无法将文件保存到闪亮应用的服务器端
- visual-studio-code - 如何在 Visual Studio Code 中触发参数提示?
- javascript - 通过选择菜单更改工具提示的效果
- .htaccess - htaccess 使用搜索查询重定向