Why do I need a parameter in a primary constructor without val/var modifier in Kotlin?

為{幸葍}努か 提交于 2021-02-05 06:40:29

问题


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 varor 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!