Get up to 80 % extra points for free! More info:

Lesson 2 - Variables, type system and parsing in Kotlin

Lesson highlights

Are you looking for a quick reference on Kotlin variables, type system and parsing instead of a thorough-full lesson? Here it is:

Creating an Int variable (for whole numbers) and assigning a value 56 to it:

var a: Int = 56

Reading text from the console using readLine()!! and concatenating strings with +:

println("Write something: ")
var input: String = readLine()!!
println("You wrote: " + input)

Reading numbers from the console using toInt() to make a number from text:

println("Enter a number and I'll double it: ")
var s: String = readLine()!!
var a = s.toInt() // eventually toDouble()
a = a * 2

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Introduction to Kotlin, the platform and IntelliJ, we learned how to work with IntelliJ, and created our first project to run Kotlin code. In today's Kotlin lesson, we're going to look at the so-called type system. We'll introduce basic data types, and we'll work with variables. We'll also talk about the difference between the var and val keywords.


Before we start with data types, let's make sure we understand what a variable is (if you're already familiar with programming, please excuse a short explanation). Surely, you remember variables from Math class (e.g. x), in which we could store some value, usually a number. A variable in IT is really the same thing. It's a place in computer memory where we can store some data, e.g. a username, the current time or a database of articles. This place has a certain reserved size, different variable types have different sizes, which the variable can't exceed, e.g. integer number can't be bigger than 2 147 483 647.

A variable is always of some sort of data type. It can be a number, a character, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in the memory, and be able to use it. Our computer knows, based on our declaration, how much memory the variable occupies and how to operate with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

  • In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have it internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.
  • On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a user object into a String, we'll get yelled at by the compiler.

Kotlin is a statically typed language. All variables have a fixed data type. However, we don't always have to specify this data type, the compiler will choose the appropriate one if not specified explicitly. The great advantage is that before running the program, our compiler checks whether all data types match. The dynamic typing may look advantageous, but we can't automatically check our source code and if we expect a user object somewhere and we get a decimal number instead, the error will be revealed only during the run-time and the interpreter will stop the program. Kotlin won't allow us to compile a program until it checks it for errors (this is yet another benefit to using compilers).

Let's make a sample program, so that you'll be able to apply this newly acquired knowledge. We will continue with the theoretic part of it all next time. Here are three basic data types:

  • Numbers: Int
  • Real numbers (10.12, ...): Double
  • Texts: String

Variable printing program

We'll go ahead and declare an integer variable, and name it: a, store the number 56 in it and print its content. Create a new project and name it Output (we'll create a new project for each sample program). Don't forget to write the code inside the body of the main() function like we did last time. I'll include the main() function below for the last time, write it by yourself for all the next examples.

fun main(args: Array<String>) {

    var a: Int

    a = 56



When we run the program, we'll see the number 56 in the console:

Console application

The first command declares a new variable, a, of the Int data type. This variable will be used to store integers i.e. whole numbers. The second command assigns a value to the variable using the = operator we all know from math classes. The last command is already familiar to us. It prints the content of the variable a. The console is smart and knows how to print numeric values as well.

We could make the code shorter by declaring and initializing the variable in a single step:

var a = 56

The compiler recognizes that 56 best matches the Int data type and assigns it in the background. Of course, we could also specify the type explicitly:

var a: Int = 56

We usually don't specify the types like this in Kotlin.

The same program for a real number variable would look like this:

var a = 56.6

It's almost the same as the code for integer. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.

Var vs. val

So far, we've declared variables using the var keyword. However, in the world of Kotlin, we work more often with a similar keyword, val. It's used to declare a constant variable that can not be further changed. Since we mostly don't need to change values in our programs, we use val primarily, and var only in case we plan to change the value of a variable. val ensures that a variable always has a constant value we have assigned to it the first time. This way there won't ever be a situation when some part of our code would accidentally change our variables.

We can simply try the functionality of val like this:

val a: Int

a = 56

a = 22

As you can see, IntelliJ reports an error since it's not possible to change the value of a val variable.

Kotlin val error - Kotlin Basic Constructs

Parrot program

The previous program was a bit boring, let's try to respond to user input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat (twice) what the user has written. We haven't tried to read anything from the console yet, but it's actually very simple. There is the readLine() function that returns a String from the console. Let's try to write the following code:

println("Hi I'm Lora, the virtual parrot, and i love to repeat!");
println("Type something in: ");

var input: String
input = readLine()!!

var output: String
output = input + ", " + input + "!"


This is a little more fun, right? :) The first two lines are self-explanatory (they just print text). On the fourth line, we declare a String input. input will contain the return value of the readLine() function, i.e. whatever the user entered to the console. Don't worry about the exclamation marks for now, they are there so we don't have to validate the input. To make the code more understandable, we create another String variable for the output. The interesting part of the code is when we assign the value to output, we do a string concatenation. We use the + operator to join several strings into one. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by a space, then input again and finally an exclamation mark. Then the program will display this variable and terminate.

Hi I'm Lora, the virtual parrot, and I love to repeat!
Say something:
Lora wants a cracker!
Lora wants a cracker!, Lora wants a cracker!!

We can assign values to variables right in their declaration, so we could replace:

var input: String
input = readLine()!!


val input = readLine()!!

We could shorten the program in many other ways, but generally, it's better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Doubler program

The doubler program will retrieve an input number, double it and display it. With the current knowledge we possess, we could write something like this:

println("Enter a number and I'll double it: ")

var a: Int = readLine()!!
a = a * 2

Notice multiplying the number a by an assignment. Kotlin will report an error and highlight the line on which we tried to get the value from the console and store it into the Int variable. We've just seen type checking in action, readLine() returns a String, and we're trying to assign it to the Int variable. Everything from the console is text, even if we enter a number. We need to parse it first.


Parsing means converting from text to another specific type, e.g. numbers. In many cases, you get data from the user or some service as String but you need it to be, for example, Int or Double for further calculations. Parsing in Kotlin is very easy, however, it has an important catch. We'll talk about it down below. If we want to parse an Int from a String, we write the following:

val a = "343".toInt()

We can see that the String data type offers the toInt() method for converting to the Int type. The method takes a string parameter and returns the string converted to an integer. We'll discuss similar methods further in the course. Let's use this in our program:

println("Enter a number and I'll double it: ")
val input = readLine()!!
var a = input.toInt() // eventually Double
a = a * 2

In the case of parsing to Double, we'd use a similar method:

var parsedDouble = "34.2".toDouble()

Of course, parsing doesn't have to be successful. Imagine that the text would be "word" instead of a number. If you try to parse anything that isn't a number, the application will crash. IntelliJ would print a red highlighted text Exception in thread 'main' java.lang.NumberFormatException: For input string: `"word"`.

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.

println("Welcome to calculator")
println("Enter the first number:")
val a = readLine()!!.toDouble()
println("Enter the second number:")
val b = readLine()!!.toDouble()
val sum = a + b
val difference = a - b
val product = a * b
val quotient = a / b
println("Sum: ${sum}")
println("Difference: ${difference}")
println("Product: ${product}")
println("Quotient: ${quotient}")
println("Thank you for using calculator.")

The output:

Welcome to calculator!
Enter first number:
Enter second number:
Sum: 5.86
Difference: 0.41999999999999993
Product: 8.5408
Quotient: 1.1544117647058822
Thank you for using calculator.

Notice 2 things. First, we simplified parsing from the console, so we don't need a String variable (we wouldn't use it further anyway). Secondly, at the end of the program, we need to print the numbers and some text before them. In order to insert the content of our variables into text, we "wrap" our numbers (or anything else) into ${}. This practice is called String Templating, and the expression inside ${} is evaluated internally. We could even perform operations such as multiplication there.

You may have thought that we could have even printed the sum of the two variables just as simple as this:

println("Sum ${a + b}")

You're right :) In the next lesson, Solved tasks for Kotlin lessons 1-2, we'll talk some more about type systems, and introduce you all to more data types.

In the following exercise, Solved tasks for Kotlin lessons 1-2, we're gonna practice our knowledge from previous lessons.


Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.


By downloading the following file, you agree to the license terms

Downloaded 23x (24.26 kB)
Application includes source codes in language Kotlin


Previous article
Introduction to Kotlin, the platform and IntelliJ
All articles in this section
Kotlin Basic Constructs
Skip article
(not recommended)
Solved tasks for Kotlin lessons 1-2
Article has been written for you by Samuel Kodytek
User rating:
5 votes
I'm intereseted in JVM languages and Swift