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?
It is as simple as the following:
This will generate a constructor accepting an
Intas its single parameter, which is then assigned to thewidgetCountproperty.This will also generate no setter (because it is
val) or getter (because it isprivate) for thewidgetCountproperty.