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?
For example: constructor(name: String, id: Int, password: String): this(password){ println("Name = ${name}") println("Id = ${id}") println("Password = ${password}")
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.
In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class. Secondary constructor - allows you to put additional initialization logic.
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.
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 this: constructor parameters are available during initialization of properties.
class Scratch(strParam:String) {
private val strMember = strParam.trim()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With