-2

I have seen some tutorials use val when creating an instance of class and some use var. I understand how val and var are different when declaring variables. However, I could not understand when we should use var and when should we use val when creating objects?

Sahran
  • 11
  • Its the same thing for objects but in terms of the ability to assign different object to the instance. You can change the object using setters but cant reassign to a different one in case you use val. – Alex Karamfilov Oct 22 '22 at 21:56
  • 3
    Does this answer your question? [What is the difference between var and val in Kotlin?](https://stackoverflow.com/questions/44200075/what-is-the-difference-between-var-and-val-in-kotlin) – jsamol Oct 22 '22 at 22:01
  • Because of design of your code, and make less mistakes – Pemassi Oct 23 '22 at 09:57

1 Answers1

1

A property is just some value associated with an object:

class MyClass {
    var someProperty: String = "wow"
}

If it's a val it's read-only and can't be changed. If it's a var then you can set a different value on that property later.


You can initialise properties based on parameters passed into the constructor:

class Rectangle(width: Int, height: Int) {
    val width: Int = width
    val height: Int = height
    val area: Int = width * height
}

But instead of creating properties and copying their values from the constructor parameters like that, Kotlin lets you take a shortcut. You can make those constructor parameters into properties just by adding the val or var keyword:

class Rectangle(val width: Int, val height: Int) {
    val area: Int = width * height
}

It's basically the same code as before, just shorter! The area property is still defined inside the class, because it's not a value that should be passed in as a parameter - it's a value that's derived from the two that the caller does provide.


So now you know that you basically are creating a variable here, hopefully it's more obvious whether you should use val or var - does the variable need to be changeable? If so, you need a var. If not, always default to val. Whether you're defining the variable in a function, in the top level of a class, or as a property in the constructor, it's all the same thing

cactustictacs
  • 17,935
  • 2
  • 14
  • 25