简体   繁体   中英

How to print the value of getter method

I created the below example in eclipse. I am following a tutorial, and it mentioned that I can use print(s1.captain) to print the captain name for example. The tutorial wants to show that kotlin automatically generate the setters and getters .

In my code the print statement does not print any thing

Main :

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")

In Kotlin, constructor arguments are only turned into properties if they are marked as val or var . In your case, captain , capacity , name , and location are just arguments to the constructor. They aren't made into properties.

To get captain and capacity as properties, add val to them:

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:

abstract class Stronghold(val name: String, val location: String)
//                        ^^^               ^^^
//                        add               add

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM