Kotlin Notes Help

Basics

Kotlin is a statically-typed language.

This means that the variable type is resolved at compile time and never changes.

Program entry point

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

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

Another form of main accepts a variable number of String arguments:

fun main(args: Array<String>) { println(args.contentToString()) }

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

A function that returns no meaningful value:

fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }

Unit return type can be omitted:

fun printSum(a: Int, b: Int) { println("sum of $a and $b is ${a + b}") }

Variables

The val keyword is used to declare immutable, read-only local variables that can’t be reassigned a different value after initialization.

val x: Int = 5

The var keyword is used to mutable variables, and their values can be changed after initialization.

var x: Int = 5 // Reassigns a new value of 6 to the variable x x += 1

Kotlin supports type inference and automatically identifies the data type of a declared variable.

// Declares the variable x with the value of 5;`Int` type is inferred val x = 5

Variables can also be declared and initialised separately

val NUM: Int // Initializes the variable c after declaration NUM = 3
Last modified: 14 February 2024