VolodymyrH
VolodymyrH

Reputation: 2019

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

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?

Upvotes: 6

Views: 1065

Answers (2)

JavierSA
JavierSA

Reputation: 801

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()
}

Upvotes: 10

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

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].

Upvotes: 6

Related Questions