Open menu with table of contents Kotlin Introduction
Logo of Stuttgart Media University for light theme Logo of Stuttgart Media University for dark theme
Android Development

Kotlin Introduction

Stuttgart Media University

1 Basic About Kotlin

  • First appeared: July 22, 2011
  • Designed and developed by JetBrains
  • Kotlin is a modern but already mature programming language designed to make developers happier. It's concise, safe, interoperable with Java and other languages, and provides many ways to reuse code between multiple platforms for productive programming.
  • Since the release of Android Studio 3.0 in October 2017, Kotlin has been included as an alternative to the standard Java compiler.
  • On 7 May 2019, Google announced that the Kotlin programming language was now its preferred language for Android app developers.

2 Basic Syntax

Please check Kotlin Basic Syntax for further information.

2.1 Package definition and imports

Package specification should be at the top of the source file. It is not required to match directories and packages: source files can be placed arbitrarily in the file system.

package my.demo

import kotlin.text.*

// ...

2.2 Program entry point

An entry point of a Kotlin application is the main function.

fun main() {
    println("Hello world!")
}

print prints its argument to the standard output.

print("Hello")

println prints its arguments and adds a line break, so that the next thing you print appears on the next line.

println("Hello world!")
println(42)

2.4 Functions

A function with two Int parameters and Int return type.

fun sum(a: Int, b: Int): Int {
    return a + b
}

A function body can be an expression. Its return type is inferred.

fun sum(a: Int, b: Int) = a + b

2.5 Variables

Read-only local variables are defined using the keyword val. They can be assigned a value only once.

val a: Int = 1  // immediate assignment
val b = 2   // `Int` type is inferred
val c: Int  // Type required when no initializer is provided
c = 3       // deferred assignment

Variables that can be reassigned use the var keyword.

var x = 5 // `Int` type is inferred
x += 1

You can declare variables at the top level.

val PI = 3.14
var x = 0

fun incrementX() {
    x += 1
}

2.6 Creating classes and instances

To define a class, use the class keyword.

class Shape

Properties of a class can be listed in its declaration or body.

class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}

The default constructor with parameters listed in the class declaration is available automatically.

val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")

Inheritance between classes is declared by a colon (:). Classes are final by default; to make a class inheritable, mark it as open.

open class Shape

class Rectangle(var height: Double, var length: Double): Shape() {
    var perimeter = (height + length) * 2
}

2.7 Comments

Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.

// This is an end-of-line comment

/* This is a block comment 
on multiple lines. */

2.8 String templates

var a = 1
// simple name in template:
val s1 = "a is $a"

a = 2
// arbitrary expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"

2.9 Conditional expressions

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

2.10 for loop

val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
    println(item)
}

//or

val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
    println("item at $index is ${items[index]}")
}

2.11 Ranges

Check if a number is within a range using in operator.

val x = 10
val y = 9
if (x in 1..y+1) {
    println("fits in range")
}

2.12 Nullable values and null checks

A reference must be explicitly marked as nullable when null value is possible. Nullable type names have ? at the end.

Return null if str does not hold an integer:

fun parseInt(str: String): Int? { 
    // ...
}

2.13 Type checks and automatic casts

The is operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly:

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    } 
    // `obj` is still of type `Any` outside of the type-checked branch 
    return null
}

3 Further Information

Check out the following websites for further information:

Questions?