audiophile121
audiophile121

Reputation: 66

Populating base class members using constants in Kotlin

If I'm creating a subclass, how can I use constants to populate members from the base class without passing via constructor. When an instance of B is created, the caller should never need to know the id used, it can be part of class B's definition. Here is what I'm currently doing with no intention of actually passing an id when instantiating class B.

abstract class A (_id: Int) {
  val id = _id
}

class B (id: Int = 99, otherParam: String): A(id) {
  val otherParam = _otherParam
}

Upvotes: 0

Views: 36

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17701

You can just use constants then:

class B (_otherParam: String): A(99) {
    val otherParam = _otherParam
}

Also, your A can be simply:

abstract class A (val id: Int) 

You don't need constructor arguments.

Same is true for B:

class B (otherParam: String): A(99) 

Upvotes: 1

Related Questions