0

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")
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

3

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
Todd
  • 30,472
  • 11
  • 81
  • 89
  • you may also want to turn them into data classes to get a default `toString` implementation – Nikky Sep 16 '18 at 14:24