Search code examples
constructorkotlinfinal

How can I modify val members during construction in Kotlin


In Java I'm able to modify final members in the constructor. Please see the following example

class Scratch {

  private final String strMember;

  public Scratch(String strParam) {
    this.strMember = strParam.trim();
  }        
}

Is there a way in Kotlin to modify val members during construction, in this case to trim() them before the parameter value are assigned to the field.

If not, what is the recommended workaround to do so without generating too much overhead?


Solution

  • You can declare an argument to the constructor that isn't marked with val or var. This has the effect of being local to the constructor and lost once class construction is complete. Take that argument and set it to whatever you want.

    class Scratch(str: String) {
        private val strMember = str.trim()
    }