Kotlin Basics: Variables, Data Types, Control Flow, Functions

Welcome to the second part of the Kotlin tutorial series! đź‘‹ In this tutorial, we will learn about Kotlin syntax, dive into variables and data types and cover control flow and functions.

Let’s get started!

 

Basic Kotlin Structure

Every Kotlin program starts with a main function. Think of it as the main door of a house; just like we need to open the door to enter a house, the programs begins by entering the main function.

This main function is the starting point for every Kotlin program. All program logic must either reside in or be initiated from here.

If we look at the first code that your wrote in the previous tutorial,

HelloWorld.kt
fun main() {
println("Hello World!")
}

This the the main function. The Kotlin Interpreter looks for this function and starts program execution from here.

 

Kotlin Variables

A variable is a placeholder for data that may either remain constant or change over time. Once declared, we can reassign a mutable variable to a new value as many times as needed.

To declare a mutable (changeable) variable in Kotlin, we use the var keyword:

VariableDeclarationVar.kt
var color = "blue"

In contrast, to declare an immutable (unchangeable) variable, we use the val keyword. This data cannot change after it’s assigned.

VariableDeclarationVal.kt
val color = "green"

With val, we can only use the assignment (=) operator once. Attempting to assign a new value to a val variable will result in a compile-time error (an error that occurs during code compilation).

valReassignment

Variables - Null assignment

Both mutable and immutable variables can be assigned a null value, representing an absence of data or a “non-existent” value.

VariableDeclarationVal.kt
var color: String? = null
val month: String? = null

Note: In Kotlin, variables need to be explicitly marked as nullable (using ? after the type) to hold a null value. Otherwise, a non-nullable variable will cause a compile-time error if you try to assign null to it.

 

Kotlin Data types

Kotlin defines couple of data types that can be used to express the types of variables.

We can define numbers whether whole or with decimal points, booleans, characters, strings and arrays.

Numbers

Numbers in Kotlin can either be whole numbers or floating-point numbers.

  • To express a whole number, we can use Byte, Short, Int, or Long.
  • To represent a floating-point number, we use Float or Double.

Byte

Byte is used to resentent a single whole digit number that ranges from -128 to 127.

ByteDataType.kt
val byteNumber: Byte = 100

Short

Short holds larger whole numbers than Byte. It occupies 16 bits and has a range of -32,768 to 32,767.

Example:

ShortDataType.kt
val shortValue: Short = 30000

Int

Int is the most commonly used data type for whole numbers. It is 32 bits and can represent values from -2,147,483,648 to 2,147,483,647.

Example:

IntDataType.kt
val intValue: Int = 2_000_000

Long

Long is used for extremely large whole numbers. It is 64 bits and supports values ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. When using Long, the number must end with an L.

Example:

LongDataType.kt
val longValue: Long = 9_223_372_036_854_775_807L

Float

Float is used for floating-point numbers and occupies 32 bits. It provides precision for up to 7 significant decimal digits and is typically used when memory is a concern. To define a Float, append F to the value.

Example:

FloatDataType.kt
val floatValue: Float = 3.14F

Double

Double is the default for floating-point numbers and occupies 64 bits. It provides precision for up to 15–16 significant decimal digits and is ideal for precise calculations.

Example:

DoubleDataType.kt
val doubleValue: Double = 2.718281828459045

Note: Inserting a number outside the range of a specific type results in a compile-time error. For example, trying to assign a number larger than 127 to a Byte variable will produce a compile-time error.

byteRange

Booleans

Booleans are used to represent logical values, typically true or false.

For example:

BooleanDataType.kt
val isKotlinFun: Boolean = true
val isOlderThan18: Boolean = false


Characters

Characters are used to represent a single digit number or letter or special character.

For example:

CharacterDataType.kt
val letter = "a"


Strings

Strings are used to represent a sequence of characters, which can include letters, digits and special characters.

For example:

StringDataType.kt
val color = "blue"
val orderNumber = "5"


Arrays

Arrays are a data structure used to store multiple elements of the same type within a single variable. They allow you to access elements by their index (position in the array). Arrays in Kotlin are fixed in size, meaning that once an array is created, its size cannot be changed. However, you can modify the values of the elements within the array.

To declare an array, you can use the arrayOf() function, which initializes the array with a set of values. The type of elements in the array is inferred automatically based on the values provided.

For example:

ArrayDataType.kt
val colors = arrayOf("blue", "green", "pink")

In this case, colors is an array of String elements with 3 colors: “blue”, “green”, and “pink”.

You can access individual elements of the array by specifying their index in square brackets []. Note that array indices in Kotlin are zero-based, which means the first element has an index of 0.

For example:

ArrayAccess.kt
val firstColor = colors[0] // "blue"
val secondColor = colors[1] // "green"

If you want to know how many elements are present within an array, you can use the size property:

ArraySize.kt
val size = colors.size // 3

 

Kotlin Operators

In order to perform arithmetic operations, we use operators. Kotlin has different type of operators that can be used.

Kotlin Control Flow

We use control flow to control the execution flow of a program. Using a conditional statement (if, else, when) we tell the program what to execute if some conditions are met.
Using loops (for loops) we iterate through some elements and run some code for each.

For example, if we want to provide a rabait on bus cards based for diffeent age groups. We can make use of if, else or when to do so. Let’s say, people less than 12 years old should have a rabait of 50%. Those less than 18 years old a rabait of 25% and those 18 years or older, a rabait of 5%.

if, else statement

when statement

 

Kotlin Functions

Â