Skip to main content

Command Palette

Search for a command to run...

Kotlin Fundamentals

Updated
5 min read
Kotlin Fundamentals
A

I'm Ajim, a Cloud DevOps Engineer from Cameroon. I'm really into Cloud Native Solutions involving Microservices, Containers, and Kubernetes. Feel free to reach out to me if you wish to connect or collaborate on a project.

Kotlin is a statically typed multi-paradigm programming language developed by JetBrains and runs on the Java Virtual Machine (JVM). Kotlin is the official language for developing Android applications and also has use cases in other areas like server-side web development and cross-platform application development with Kotlin Multiplatform.

This guide is primarily targeted at individuals who have prior experience in another programming language and want to get acquainted with Kotlin's syntax. However, anyone interested in reading is still welcome.

This guide covers variables, control flow, and functions, as these are the fundamental concepts of most modern programming languages. More intermediate to advanced concepts like object-oriented programming and functional programming will be covered in future guides.

Tip💡: You can use the kotlin playground to run all the sample code in this tutorial.

Variables

Declaration

In Kotlin, variables are declared in this format keyword variable_name : Type = value. The var keyword is used to declare mutable variables (variables that can be reassigned a different value) and val for immutable variables (cannot be reassigned). It is common practice to follow the camel case naming convention for variables in Kotlin. The following example demonstrates declaring variables of various types. You can find the full list of available types here.

fun main() {

    val name : String = "Ajim"
    val age : Int = 23
    val gender : Char = 'M'
    val gpa : Double  = 3.87
    val isEmployed: Boolean = false

}

Note: Specifying the type is optional when assigning a value during declaration, as Kotlin can automatically infer it.

I/O Operations

fun main() {

    var name: String = ""

    name = readln()

    // template string
    println("Hello $name!")

}

In the above example, name is declared and assigned an empty string. The readln() function gets the user's input and println() prints the output to the console using a string template.

Control Flow

Conditional Expressions

Conditional statements can either be expressed using if or when statements in Kotlin. when is similar to “switch case statements” in other programming languages and is suitable for evaluating a variable against discrete values or simply making code more readable.

If statement example:

val number = 10

if (number >= 0) {
    println("Number is a positive number")
} else {
    println("Number is a negative number")
}

When statement example:

val grade: Char = readln().first()

when (grade) {
    'A' -> println("Excellent")
    'B' -> println("Very Good")
    'C' -> println("Good")
    else -> println("Failed")
}

Unlike other programming languages, if and when statements in Kotlin can be used to initialize a variable:

val age = 12

val ageGroup = if (age <= 11) {
   "kid"
} else if (age <= 19) {
   "teenager"
} else {
   "adult"
}

The same thing as above with when:

val age = 12

val ageGroup = when (age) {
    in 0..11 -> "kid"
    in 12..19 -> "teenager"
    else -> "adult"
}

It is also possible to one-line an if statement:

val x = 2;
val z = if (x == 2) 2 else 3

Note: Kotlin doesn't have a ternary operator like we might know from other languages, however the if expression functions the same way.

Loops

Kotlin has the for loop, while loop, and do-while loop. The for loop is suitable for iterating over a range of values (or lists), while the while and do-while loops are suitable for cases where a piece of logic has to be run until a certain condition is met.

For Loop

for (i in 1..10){
    println(i)
}

The code above is a simple for loop that prints numbers from 1 to 10.

Notice 1..10 in the for loop's parenthesis. This is known as a range in Kotlin, and it basically denotes a range of numbers between 1 and 10 inclusive. In other languages (e.g C), we'd have something like this instead: for(i = 1, i≤ 10, i++).

Example iterating over a list of items:

val cities = listOf<String>("Tokyo","Nairobi", "Rio", "Denver",  "Berlin" )

for (city in cities) {
    println(city)
}

While Loop

var counter = 1

while (counter <= 10) {
    println(counter)
    counter++
}

The snippet above is a simple while loop that prints numbers from 1 to 10.

Do-While Loop

var counter = 1

do {
    println(counter)
    counter++
} while (counter <= 10)

Printing numbers from 1 to 10 in the do-while loop.

Functions

fun sum(x: Int, y: Int): Int {
    return x + y
}

fun main() {

    val z = sum(2, 3)

    println(z)

}

Functions in Kotlin are declared using the keyword fun. In the sample code above, a sum() function is declared that accepts two integers x and y, and returns an integer that is the sum of both inputs. The main() function gets called automatically when the program is run. sum() is called in the main() function, with arguments 2 and 3, and the return value is then stored in a variable named z.

When defining a function, default values can also be assigned as parameters:

fun sum(x: Int = 2, y: Int = 3): Int {
    return x + y
}

fun main() {
    println(sum())
}

Lambda Expressions

Lambda expressions are a little more advanced, but because they are frequently used in Kotlin, it is worth taking a look at. Lambdas work like regular functions, but they are shorter (usually one line) and mostly used as arguments to other functions. This is a simple example of a sum function expressed as a lambda.

fun main(){
    val sum = { x: Int, y: Int -> x + y }
    println(sum(2,3))
}

Explicitly defining a lambda's type:

val sum: (Int, Int) -> Int = { a, b -> a + b }
println(sum(2,3))

Note: Defining a lambda's type is optional. However, if the type isn't defined, the parameter types have to be defined in the lambda expression.

Conclusion

This guide covered the fundamental aspects of the Kotlin programming language: variables, conditional statements, loops, and functions. However, there is more to Kotlin that we will cover in future guides. You are welcome to subscribe to my newsletter so you get notified when I publish a new article. I hope you found this guide helpful, and I look forward to seeing you in the next post.