Extra members from constructor parameters

I’m fairly new to Kotlin. When I want to initialize class members with values from the constructor arguments, I can just put val in front:

class RegularStringStore(val text: String) {
  fun printText() {
    print(text)
  }
}

But if I want to use the constructor arguments to initialize another object and store that in a class member, how should I do that? Example:

class UppercasedStringStore(text: String) {
  fun printText() {
    print(uppercased)
  }
}

Where can I create uppercased?

Assume uppercased should not be nullable and I want to create it when UppercasedStringStore is instantiated, not lazily. Also, after uppercased has been initialized, I don’t want to keep text around.

Ok, I figured it out. The answer is “nowhere special”.

class UppercasedStringStore(text: String) {

  val uppercased = text.uppercase()

  fun printText() {
    print(uppercased)
  }
}
1 Like

You can also use the init block.