[英]How to print the value of getter method
I created the below example in eclipse. 我在eclipse中创建了以下示例。 I am following a tutorial, and it mentioned that I can use print(s1.captain)
to print the captain name for example. 我正在学习一个教程,它提到我可以使用print(s1.captain)
打印队长名称。 The tutorial wants to show that kotlin
automatically generate the setters
and getters
. 该教程希望表明kotlin
自动生成setters
和getters
。
In my code the print statement does not print any thing 在我的代码中,print语句不打印任何东西
Main : 主要 :
fun main(args : Array<String>) {
var s1 = Stronghold1("JJ",7)
print(s1.captain)
}
stronghold : 要塞 :
abstract class Stronghold(name: String, location: String)
stronghold1 stronghold1
class Stronghold1(captain: String, capacity: Int) : Stronghold("GerMachine", "Bonn")
In Kotlin, constructor arguments are only turned into properties if they are marked as val
or var
. 在Kotlin中,只有将构造函数参数标记为val
或var
它们才会变为属性。 In your case, captain
, capacity
, name
, and location
are just arguments to the constructor. 在您的情况下, captain
, capacity
, name
和location
只是构造函数的参数。 They aren't made into properties. 它们不是属性。
To get captain
and capacity
as properties, add val
to them: 要将captain
和capacity
作为属性,请向其添加val
:
class Stronghold1(val captain: String, val capacity: Int) : Stronghold("GerMachine", "Bonn")
// ^^^ ^^^
// add add
You probably want to do the same thing with Stronghold
as well: 您可能还想对Stronghold
做同样的事情:
abstract class Stronghold(val name: String, val location: String)
// ^^^ ^^^
// add add
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.