Home > Back-end >  How do you initialize val fields with constructor params in Kotlin?
How do you initialize val fields with constructor params in Kotlin?

Time:12-26

In Java you can declare a private final member variable and then initialize it from your constructor, which is very useful and is a very common thing to do:

class MyClass {

  private final int widgetCount;

  public MyClass(int widgetCount) {
    this.widgetCount = widgetCount;
  }

In Kotlin how do you initialize final member variables (val types) with values passed in to a constructor?

CodePudding user response:

It is as simple as the following:

class MyClass(private val widgetCount: Int)

This will generate a constructor accepting an Int as its single parameter, which is then assigned to the widgetCount property.

This will also generate no setter (because it is val) or getter (because it is private) for the widgetCount property.

CodePudding user response:

class MyClass(private val widgetCount: Int)

That's it. If in Java you also have a trivial getter public int getWidgetCount() { return widgetCount; }, remove private.

See the documentation for more details (in particular, under "Kotlin has a concise syntax for declaring properties and initializing them from the primary constructor").

  • Related