Variables in Kotlin, differences with Java. var vs val (KAD 02)

In this second chapter we will see how variables work in Kotlin, what is val and var , and when to use one or the other.

I wanted to start from here, because it will be useful to understand later how to create “fields” in our classes (we will see that they are not exactly fields).

If you prefer the video format, in this one I explain how to create your first project from scratch, and everything about variables:

Variables in Kotlin

Variables in Kotlin allow, as in Java, to assign values ​​that can then be modified and used at different points in our program, as long as they are within the scope in which the code is executed.

But I’m going to focus on the differences we find with Java.

1. The variables can be mutable and immutable

This can also be done in Java (marking variables as final if we don’t want it to be modified), but in Kotlin it is much less verbose and much more used: In Kotlin immutable values ​​are preferred whenever possible.

The fact that most parts of our program are immutable provides lots of benefits, such as a more predictable behaviour and thread safety.

2. Variables are declared using val or var , provided they are immutable or mutable

An interesting thing from Kotlin is that most of the time you won’t need to specify the type of the objects you are working with, as long as the compiler can infer it.

So we just need to write var or val depending on the type of variable we want to generate, and the type can normally be inferred. We can always specify a type explicitly.

Some examples:

var x = 7
var y: String = "my String"
var z = View(this)

Spoiler: As you see, you do not need to use new to create a new instance of an object.

3. Type casting is done automatically

Whenever the compiler is able to detect that there is no other possible option, the casting will be done automatically. Awesome!

val z: View = findViewById(R.id.my_view)

if (z is TextView) {
    z.text = "I've been casted!"
}

Did you see that I did not call setText() ? I will explain it in next articles!

4. In Kotlin everything is an object

There are no basic types, and there is no void . If something does not return anything, it actually returns the Unit object. Most of the time it can be omitted, but it is there, lurking.

Therefore, all these variables are objects:

val x: Int = 20
val y: Double = 21.5
val z: Unit = Unit

5. Simpler numerical types can not be assigned to more complex types

For example, an integer can not be assigned to a long variable. This does not compile:

val x: Int = 20
val y: Long = x

You need to do an explicit casting:

val x: Int = 20
val y: Long = x.toLong()

Conclusion

These are some of the most outstanding differences you can find between variables in Java and Kotlin. In general, variables in Kotlin provide much more flexibility, safety (due to the convention of using val whenever possible) and cleaner, more concise code.

Any doubts? Get ready for the next article!

And if you want to learn how to use Kotlin to develop your own Android Apps, I recommend you take a look at my free training. Reserve your place!

14 thoughts on “Variables in Kotlin, differences with Java. var vs val (KAD 02)”

  1. > “The variables can be mutable and immutable”
    They are not immutable, “val” is exactly like “final” in java – it only makes reference read-only, but not the actual object immutable.

    > “In Kotlin immutable values ​​are preferred whenever possible.”
    This is also valid for java.

  2. Hi, thanks for explanation, but I am still confused with the 4th point about “If something does not return anything, it actually returns the Unit object.” can i get more explanations and code samples. Thank You.

    1. In Kotlin everything returns a value. In Java, you can have functions that return nothing (setting `void` as return), but that’s not the case of Kotlin. The closest thing to return is `Unit`, which represent the empty value. Thanks to this, you can deal with all functions in a generic way, because they always return something, so you can always assign the result to variable for instance. You can write a function when you don’t specify the return value, but that will be the same as setting that it returns `Unit`.

  3. this will be useful in cases like function overloading whether function 1 returns unit or function 2 returns some values

    am I correct ?

    1. Yeah, as functions always return a value, you can make easier standarization of your code. Because you now know that a function always return something, the same you know that a type is always an object. All that simplifies coding a lot.

  4. Hi dear Antonio, I always had little problem to setting variables view found by ID to “var”, but I want to use “val”
    what is best practice to set views on field val.

    For example:

    private var someTextView:TextView ?= null


    override fun onViewCreated(view:View, @Nullable savedInstanceState: Bundle) {
    someTextView = view.findViewById(R.id.some_text_view_id)
    }

    so how to set view (findById(…)) to VAL

    thanks.

  5. Hi Antonio,
    I myslef use a lot final keyword in java but there is this situation. I have some clases as model/domain. I load Entty from db, convert to domain object, do operations on this somain object, cnvert back to entoty and store.
    I may change several properties and do not like the idea of making a copy() each time i modfy anything. So is it right appoach that in such a domain class I do val for fields like ID and var for basically all application-wise mutables? I hope I explain this well. It is more like best practice question.
    Thanks Ivan

  6. I need you help.. I m stuck somewhere..

    Actually I m developing an online quiz app using firebase database.. problems I m having:-

    1) I have home fragment (fragment class) from where I m passing data to another activity “Test” using intent.. now this Test activity is the container of another 10 fragments and from the Test activity I am passing data using companion objects in fragments which have newinstance() function.. the problem is in that activity I m accessing data from the database in the onStart() method using the passed value(which is string passed by container activity) as path of the database using which I m want to get the data..but unfortunately this passed value only gives value for the first when fragment start then it gives null value.. I don’t know y it is like that .. please help me

Comments are closed.