我在 Eclipse 中创建了以下示例。我正在关注一个教程,其中提到我可以使用 print(s1.captain)
来打印队长姓名。本教程想要展示 kotlin
自动生成 setters
和 getters
。
在我的代码中,打印语句不打印任何内容
主要:
fun main(args : Array<String>) {
var s1 = Stronghold1("JJ",7)
print(s1.captain)
}
据点:
abstract class Stronghold(name: String, location: String)
据点1
class Stronghold1(captain: String, capacity: Int) : Stronghold("GerMachine", "Bonn")
最佳答案
在 Kotlin 中,构造函数参数仅在标记为 val
或 var
时才会转换为属性。在您的例子中,captain
、capacity
、name
和 location
只是构造函数的参数。它们没有被制成属性(property)。
要获取 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
关于java - 如何打印getter方法的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52353528/