July 2018
Intermediate to advanced
400 pages
12h 14m
English
As you learned in Chapter 12, you can specify your own getter and setter for a property. Now that you have seen how properties and their classes are initialized, we have a riddle for you.
Every great sword has a name. Define a class called Sword in the Kotlin REPL that reflects this truth.
Listing 13.13 Defining Sword (REPL)
class Sword(_name: String) {
var name = _name
get() = "The Legendary $field"
set(value) {
field = value.toLowerCase().reversed().capitalize()
}
}
What is printed when you instantiate a Sword and reference name? (Try to answer for yourself before you check the REPL.)
Listing 13.14 Referencing name (REPL)
val sword = Sword("Excalibur")
println(sword.name)
Read now
Unlock full access