2

I am learning Spring Boot with kotlin and I am so confused with the usage of var or val for entity property. In some tutorial they use val and the other use var. So I don't know which is the right one to declare property for entity. At least enlightenment me about this. Please & Thanks!!

Denny Rustandi
  • 317
  • 2
  • 13

1 Answers1

0

val and var both are used to declare variables but the main difference between them could be defined as;

val: is used when you declare a variable with a value which you don't want to change or update, it is kind of a constant variable which can only be initialized once. And when you try to change its value, it will show an error like Val can not be reassigned. it is known as immutable variable in kotlin.

On the other hand,

var: is used when you intend to declare a general variable whose value could be changed or updated anywhere in the class. It could be initialized or reassigned multiple times and it is known as mutable variable in kotlin.

I hope this will help you. There is a good definition with example.

  • 5
    This doesn't actually answer the question - which is directly referring to the use of val and var when creating entity properties (table columns) in spring (which is a slightly different situation than a typical variable declaration) – Chaya Sulman Nov 11 '21 at 21:48