问题
If I create a class, I can pass a parameter:
class Person(name: String) {
}
I also can write the same, but with val and then I'll be able to use properties to get this value, when I created an object.
val person = Person("Name")
person.name
The question is: why do I need just a parameter without the val? Where, how and why should I use it?
回答1:
If you use var
or val
in the constructor, you are declaring properties and initializing them directly. If you don't, those parameters are used for initialization purposes:
class Customer(name: String) {
val customerKey = name.toUpperCase()
}
回答2:
https://kotlinlang.org/docs/reference/classes.html
It's used when you don't want constructor arguments to become named properties on the class.
If you use val
, you get a read-only property. If you use var
, you get a mutable property. Otherwise, you get nothing [auto-defined].
来源:https://stackoverflow.com/questions/49610775/why-do-i-need-a-parameter-in-a-primary-constructor-without-val-var-modifier-in-k