Reputation: 2978
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?
Upvotes: 14
Views: 8269
Reputation: 616
The currently accepted answer is correct in explaining why your initial attempt did not work. As such, given your particular scenario, I would inverse the solution and make your secondary constructor the primary, and make that second parameter have a default value.
data class Person(val name: String, val surname: String = "Unknown")
Also, if the class's purpose is to simply hold data, I would make it a data class
to improve its handling.
Upvotes: 1
Reputation: 11
You can define the variable as val or var in the class you inherit from
open class Human(val name: String) constructor(name: String) {
open fun showInfo()
{
println("Show Info")
}
}
class Person:Human {
constructor(name: String) : super(name)
private var surname: String = "Unknown"
override fun showInfo() {
println("$name And surname is $surname")
}
}
Upvotes: 0
Reputation: 81879
In addition to the great answer of yole, the documentation is pretty clear as well:
Note that parameters of the primary constructor can be used in the initializer blocks. They can also be used in property initializers declared in the class body. [...] In fact, for declaring properties and initializing them from the primary constructor, Kotlin has a concise syntax:
class Person(val firstName: String, val lastName: String, var age: Int) {
// ...
}
Much the same way as regular properties, the properties declared in the primary constructor can be mutable (var) or read-only (val).
This all does not apply to secondary constructors.
Upvotes: 4
Reputation: 97148
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.
Upvotes: 32