DEV Community

Raul Montero
Raul Montero

Posted on • Originally published at on

Variables and types in kotlin

All languages are different but at the same time, they have a lot of things in common, a lot of similar components.

Chances are, this is not your first language and therefore you are familiar with the concept of variables and the different common types you could expect in a language. Still, I’m going to walk you through the bits and pieces where kotlin is different so you are able to start feeling comfortable with the language’s philosophy and way to do things.

Let’s start.


A variable’s job is simple, assign a value and give it a name to be called for later. Kotlin takes this simple concept and adds some additional rules to enhance code performance and readability.


In Kotlin, variable declarations have a simple structure :

  1. var (or val) keyword to indicate the start of a variable declaration.
  2. The name of the variable.
  3. two dots followed by the variable’s type. (optional)
  4. an equal sign to assign a value to the variable.

Here is an example in action of a variable declaration

// Using var 
var a:String = "Something Interesting" 

// Using val 
val b:String = "Something even more interesting"

As you can see, we can declare a variable either using var or val keywords. The main difference between them is mutability or the capacity to change. With var, you can change the value of the variable while with val you can not, and when I say value I mean instance since in kotlin everything is an object. The object’s properties are able to change but not the instance it refers to when we use val.

Another interesting thing to note is that val-declared variables behave similar to constant values but with one major difference: val allows to assign it an expression that will resolve into a value, while the const only permits a primitive or string literals.

Here we can see an example of val vs const

val value:Int = 1+1 // Valid const 

val constant:Int = 1+1 //Invalid const 
val constant2:Int = 1 //Valid

And here with var and val

// Using var 
var a:Int = 5 
a = 6 // Valid 

// Using val 
val b:Int = 5 
b = 6 // Invalid


Kotlin doesn’t allow null values out of the box, which means you can’t declare a variable without assigning it a value right away, at least not with the standard declaration. Even using nullable values, due to kotlin’s readability-promoting philosophy, you are required to assign the value explicitly (even null) when declaring the variable’s initial state.

But what about the cases where we don’t know the value of the variable right away, like for example with instance variables in a class? We can do it, but we do it by telling kotlin our intent explicitly. We do this by using the keyword lateinit before the variable declaration.

You can think of the lateinit as a promise. A promise to initialize the variable at a later time _before _you try to use it. The compiler then believes in you and let you do it your way, but just in case you are feeling a bit adventurous, it will throw an exception if you try to access it before assigning a value.

Now, let’s see this in action

//Without lateinit 
var a:Int //Error 
a = 5 //Error 

//With lateinit 
lateinit b:Int // valid 
b.toString() // Throws exception 

b = 5 
b.toString() // valid


Kotlin is a statically-typed language, which means all variables types are evaluated at compile-time, but that doesn’t mean you need to specify the variable type explicitly. Kotlin has a system called duck-typing that allows it to infer the type based on the value it is being assigned to, saving you the need to do it yourself.

Do not be confused with the dynamic typing characteristic that is present in other languages (javascript, for example) that let you change the variable’s type at run-time depending on the value it holds. Although kotlin can infer the variable type, this happens at compile-time and once a variable type has been determined it can never be changed.


Here we will discuss the common types (or kind of information) a variable can hold out of the box. Most of them should be very familiar to you but at the same time, they come with a small twist.


Numbers (in any of their variants) are objects and as such, they hold methods and properties.

In the particular case of running kotlin on top of the JVM, those numbers are stored as primitives and in case a nullable number is used, the boxing/unboxing process is done automatically.

Something curious in kotlin is that numbers are not implicitly cast. That means you can’t assign an int variable to a long one without doing a cast beforehand.

var small:Int = 5 
var large:Long = small // Invalid 

var larger:Long = (Long) small //Valid

Another curious thing is you can add any number of underscore characters to a number literal to make it more readable and the kotlin compiler will remove those underscores and use the remaining number as its value.

This means,

var number1:Int = 1\_000 
var numer2:Int = 1000 
number1 == numer2 //Evaluates to true


Characters represent a single letter or number and pretty much any symbol you can find in the ASCII table. You define them using single quotes.

val c: Char = 'C'

In some languages, you can use the numeric representation of a character to compare to an int. In kotlin this doesn’t happen out of the box, instead, you must use the method toInt() to do the conversion.


If you have done any text manipulation in the past you will feel comfortable with strings in kotlin. The way kotlin handles strings is very standard, the methods and properties are very straightforward and easy to understand.

Here are a few key points about this data type:

  1. A String is a collection of characters, therefore can use the collection’s way of accessing their elements by using the indexing operator, and also have access to the collection’s methods to manipulate its contents.
  2. Strings are immutable, which means any operation that “modifies” an existing string, what does, in reality, is dispatching the previous string and creating a new one with the result.
  3. There are two types of strings, the ones that are escaped and the ones that aren’t. With the first type, any special character must be included explicitly through the use of special escape characters whereas the other one is sufficient to be included in the string literal.
  4. You can evaluate variables and expressions inside a string. The process is called string templates and you use it prepending the currency sign ($) before a variable or wrap it with curly braces in the case its an expression.

Alright, it’s time to put the words into actions with some examples. First, let’s use the indexing operator to get a character in a given position of a string. Just like with arrays, you use the variable name next to the opening and closing brackets with a number inside indicating the position of the element you want.

var text:String = "This is a text!" text[1] // Returns h

Now, let’s see how to escape vs not escape string compare to each other. Do notice that the raw string (not escaped) variant requires three double quotes while the escaped one just two.

In this example, we can see the escaped string doesn’t recognize the line break (newline) character inside the text while the other one does. If we wanted to have a line break, inside the escaped string we had to add the escaped character (\n) explicitly.

var escaped:String = "first line second line" // Throws a compiler error var raw:String = """first line second line""" // Valid

Finally, we’ll see how to get a variable’s value or execute an expression from inside the string literal

var age:Int = "29" 
var text:String = "Hello!, I'm Raul and I'm $age years old" // That prints Hello!, I'm Raul and I'm 29 years old 
var expression:String = "1+1 = ${1+1}" // That prints 1+1 = 2

To be continued …

I hope this was enough information to give you a rough idea of how kotlin interacts with variables and types. There is still a bit more to cover about kotlin’s main data types but we got off a good start.

Next up we’ll see arrays and collections and how they work and interact with the information they hold. We will also see Pairs which is a kotlin-specific type, very similar to tuples in other languages.

This post is part of a series aimed to give you an introduction to the language and a taste of the way kotlin does things. You can find it here:
A guide to the kotlin language

Top comments (0)