Kotlin: Variable Declarations

MJ Manaog
2 min readJun 28, 2020

According to Kotlin documentation, every variable must be declared.

In Kotlin we have var and val, what’s the difference between these two?

  • var — declares a mutable variable
  • val — declares a read-only or assign-once variable

Ok so let’s try to declare two variables:

As we can see, you do not have to specify the datatype of the variables, unless it is necessary, because Kotlin uses type inference, which means the compiler will already know or infer the type of a variable you have declared and this has done at compile-time, not at run-time.

So if we try to reassign variables in our two declarations, see Lines 9 & 10, you will get an error in Line 10. Because you cannot reassign a value to a val.

Can we say that val and constant are the same?

Actually, no. One main difference between val and const val, constant should be declared in the top-level of the file also can be declared inside an object but outside a class.

So what we’re trying to say if we do something like this:

  • Line 2: will not work because it was declared inside the top-level function
  • Line 5: will work because it was declared in the top-level of the file
  • Line 8: will work because it was declared inside an object
  • Line 11: will not work because we’ve reassigned new value using a method airport. Also because constants only accept a truly constant primitive type value that is known at compile time. The airport method can be changed especially if the people sitting on the higher table have so much spare time to prioritize a non-sense bill.
  • Line 12: just proved that val does not mean immutable, because it can be changed at runtime.

What about if I want to specify the datatype of a variable?

Again, if the context is already obvious in your declaration, you do not have to add the data type. But if you want to specify it you can do something like this:

So yep, that’s it. Kotlin is concise, therefore we must keep it that way.

--

--