Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
Jan B. Avatar asked Aug 02 '18 12:08

Jan B.


People also ask

How does Kotlin pass value in constructor?

For example: constructor(name: String, id: Int, password: String): this(password){ println("Name = ${name}") println("Id = ${id}") println("Password = ${password}")

How do you use constructor parameters in Kotlin?

The primary constructor is initialized in the class header, goes after the class name, using the constructor keyword. The parameters are optional in the primary constructor. The constructor keyword can be omitted if there is no annotations or access modifiers specified.

What are the two types of constructors in Kotlin?

In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class. Secondary constructor - allows you to put additional initialization logic.

When can you omit the constructor keyword in Kotlin?

In some cases, we can omit the constructor keyword. This is only mandatory in two cases: when we use annotations, like @Autowired or access modifiers, like private or protected. Also, we can use Kotlin default parameters in the constructors.


2 Answers

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()
}
like image 63
Todd Avatar answered Oct 11 '22 05:10

Todd


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

class Scratch(strParam:String) {
    private val strMember = strParam.trim()
}
like image 35
Demigod Avatar answered Oct 11 '22 06:10

Demigod