7

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?

Jan B.
  • 6,030
  • 5
  • 32
  • 53

3 Answers3

8

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()
}
Todd
  • 30,472
  • 11
  • 81
  • 89
  • 1
    Ah, seems pretty concise. Wouldn't work with `data` classes, though? – Jan B. Aug 02 '18 at 13:02
  • 1
    I don't think that's a good use of Data Classes, TBH. Here's a good answer (to a slightly different question, but essentially the same) covering why, and how to get around it: https://stackoverflow.com/a/46376746/49746 – Todd Aug 02 '18 at 13:08
  • And neither do I the more I'm dealing with it. Data classes tend to support anemic domain model rather than rich domain objects with multiple inheritances. – Jan B. Aug 02 '18 at 21:03
2

Like this: constructor parameters are available during initialization of properties.

class Scratch(strParam:String) {
    private val strMember = strParam.trim()
}
Demigod
  • 5,073
  • 3
  • 31
  • 49
0

Try your strParam final property as follow

class Scratch(strParam : String) {
    val strParam : String = strParam 
        get() = field.trim()
}

So, you can use them inside and outside your Scratch class

Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
  • 1
    This doesn't seem efficient since every get() call will execute `trim` and allocate new `String` instance. – Pawel Aug 02 '18 at 19:22