I have following class:
class Person(val name: String) {
private var surname: String = "Unknown"
constructor(name: String, surname: String) : this(name) {
this.surname = surname
}
}
But when I want to have the name parameter immutable in second constructor:
constructor(val name: String, surname: String) : this(name) {
this.surname = surname
}
I have the following compile-time error:
Kotlin: 'val' on secondary constructor parameter is not allowed
Can someone explain why is Kotlin compiler not allowing to do this?
Parameters in Kotlin are always immutable. Marking a constructor parameter as a val
turns it into a property of a class, and this can only be done in the primary constructor, because the set of properties of a class cannot vary depending on the constructor used to create an instance of the class.