No history yet

Kotlin Basics

Your First Look at Kotlin

Kotlin is a modern programming language that runs on the Java Virtual Machine (JVM). It was developed by JetBrains, the company behind many popular development tools. In 2019, Google announced it would be the preferred language for Android development, and for good reason.

Since Google I/O 2019, Android development has been Kotlin-first.

Kotlin is praised for being concise, safe, and fully interoperable with Java. This means you can have both Kotlin and Java code in the same project, and they'll work together seamlessly. This made it easy for existing projects to adopt Kotlin gradually.

Let's start with the classic "Hello, World!" program. Every Kotlin application needs a main entry point, which is a function called main.

fun main() {
    println("Hello, World!")
}

The fun keyword is used to declare a function. println is a standard library function that prints a line of text to the console. Unlike Java, you don't need to end your lines with a semicolon, which is one of many ways Kotlin reduces boilerplate code.

Variables and Data Types

In Kotlin, you declare variables using two keywords: val and var.

  • val is for variables whose value never changes. Think of it as a constant or a read-only value. You assign it once, and that's it.
  • var is for variables whose value can be changed later. It's a mutable variable.

It's a good practice to use val whenever possible. This makes your code safer and easier to reason about, as it reduces the chances of accidentally changing a value.

// val is for read-only variables
val language: String = "Kotlin"

// var is for mutable variables
var score: Int = 0
score = 10 // This is okay

// language = "Java" // This would cause a compiler error!

Notice how we specified the data types, like String and Int. Kotlin has several basic types, including Double for decimal numbers and Boolean for true or false values.

However, Kotlin also has powerful type inference. If you assign a value when you declare a variable, the compiler can often figure out the type on its own, making your code even more concise.

val name = "Alex" // The compiler knows this is a String
var count = 100    // The compiler knows this is an Int

Controlling the Flow

Like any programming language, Kotlin has ways to control the execution flow of your code. You can make decisions and run code repeatedly.

The if statement is a basic conditional. In Kotlin, if can also be used as an expression, meaning it can return a value.

val temperature = 25

val weather = if (temperature > 20) {
    "It's warm!"
} else {
    "It's chilly."
}

println(weather) // Prints: It's warm!

For more complex conditions, Kotlin provides the when expression. It's like a supercharged switch statement from other languages. It can match against values, ranges, or even types.

val dayOfWeek = 5

val dayType = when (dayOfWeek) {
    1 -> "Sunday"
    in 2..6 -> "Weekday"
    7 -> "Saturday"
    else -> "Invalid day"
}

println(dayType) // Prints: Weekday

To repeat actions, you can use loops. The for loop is great for iterating through a range of numbers or items in a collection.

// Prints numbers from 1 to 5
for (i in 1..5) {
    println(i)
}

There is also a while loop that continues as long as a condition is true, which works just as you'd expect from other languages.

Building with Functions

Functions are reusable blocks of code that perform a specific task. We've already seen the main function. You declare them using the fun keyword, followed by the function name, parameters in parentheses, and an optional return type.

// This function takes two integers and returns their sum
fun add(a: Int, b: Int): Int {
    return a + b
}

// You can call it like this
val sum = add(5, 3) // sum is 8

For very simple functions that consist of a single expression, you can make the syntax even shorter:

fun multiply(a: Int, b: Int): Int = a * b

Kotlin also has first-class support for lambdas, which are essentially anonymous functions. You can treat them like values, passing them to other functions or storing them in variables. This is a powerful feature for functional programming.

A lambda expression is always surrounded by curly braces {}. Its parameters are declared before the -> arrow, and the body comes after.

// A lambda that takes two Ints and returns their sum
val sumLambda: (Int, Int) -> Int = { a, b -> a + b }

val result = sumLambda(10, 20) // result is 30

Classes and Objects

Kotlin is an object-oriented language. The fundamental building block of object-oriented programming is the class, which acts as a blueprint for creating objects.

Here’s a simple class to represent a User.

class User(val name: String, val age: Int) {
    fun greet() {
        println("Hello, my name is $name.")
    }
}

// Create an instance (object) of the User class
val user = User("Alice", 28)
user.greet() // Prints: Hello, my name is Alice.

That class User(...) line defines a class with a primary constructor. The properties name and age are declared right in the constructor. The greet() function is a method of the User class. Creating an object, or an instance of a class, is as simple as calling the constructor like a function.

Kotlin also supports inheritance, allowing one class to inherit properties and methods from another. You use a colon : to indicate inheritance. By default, classes in Kotlin are final (they can't be inherited from), so you need to mark the parent class with the open keyword.

// The parent class must be 'open'
open class Vehicle(val speed: Int)

// Car inherits from Vehicle
class Car(speed: Int, val brand: String) : Vehicle(speed)

val myCar = Car(120, "Tesla")
println("My ${myCar.brand} can go ${myCar.speed} km/h.")

These are the fundamental building blocks of Kotlin. With variables, control flow, functions, and classes, you have everything you need to start writing powerful programs.

Quiz Questions 1/6

In Kotlin, which keyword is used to declare a variable whose value cannot be changed after its initial assignment?

Quiz Questions 2/6

True or False: Kotlin code must be in a separate project from Java code and cannot interact with it.