我在eclipse中创建了以下示例。我正在学习一个教程,它提到我可以使用print(s1.captain)
来打印队长的姓名。本教程希望证明kotlin
自动生成setters
和getters
。
在我的代码中,print语句不打印任何东西
主要:
fun main(args : Array<String>) {
var s1 = Stronghold1("JJ",7)
print(s1.captain)
}
stronghold :
abstract class Stronghold(name: String, location: String)
stronghold1
class Stronghold1(captain: String, capacity: Int) : Stronghold("GerMachine", "Bonn")
答案 0 :(得分:3)
在Kotlin中,只有将构造函数参数标记为val
或var
时,它们才会变成属性。在您的情况下,captain
,capacity
,name
和location
只是构造函数的参数。它们不是属性。
要获取captain
和capacity
作为属性,请向其中添加val
:
class Stronghold1(val captain: String, val capacity: Int) : Stronghold("GerMachine", "Bonn")
// ^^^ ^^^
// add add
您可能还想对Stronghold
做同样的事情:
abstract class Stronghold(val name: String, val location: String)
// ^^^ ^^^
// add add