DEV Community

Cover image for How to declare a variable? Kotlin Tutorial
Adrian Bornea
Adrian Bornea

Posted on

How to declare a variable? Kotlin Tutorial

A program is nothing without data. Let's find out how to declare a variable in Kotlin.
Stop 🛑 Do you want to learn Kotlin with me? I will post multiple times per week new things I've learned about this programming language.

There are two ways to declare a variable in Kotlin:

1. Using the "val" keyword

// constant, immutable, read-only & final
val city: String = "Paris"

Basically once we declare it we can't change it.
city = "Rome" // will throw an error

2. Using the "var" keyword

// mutable variable
var country: String = "Italy"

Now we can re-use the same variable. We can mutate the object.
country = "France"

Kotlin is smart and can guess the type for a declared variable. I think this will make you a negligent programmer in the long run.
// type inference
var language = "Java"
// the compiler will know it's String

Once the type is established we can't change it
language = 12 // will throw an error

I want these articles to be living entities, so I will edit them along the way with new/interesting I find about a particular subject.

Image by _ferh97

Top comments (0)