02. Introduction to Kotlin

Designed by IntelliJ (first released 2011) as a modern replacement to Java, with a less verbose syntax and with support for a more functional style of programming (immutability, higher-order functions, and type inference).

In 2017, Google declared Kotlin an official language for Android development.


@file:JvmName("Main")
// Name of the Java class as the function below is in global scope

fun main(args: Array<String>) {
  println("Hello, World!")
}

Variables:

Types:

String templating:

Collections:

Conditional statements

Switch:

Functions:

fun name(param1: Type, param2: Type): ReturnType {

}

fun singleLine() = Random.nextInt(100)

Classes:

class Point(x: Float, y: Float) {
  var x: Float = x
  var y: Float = y

  // Can also use `val` for constants
}

// Same variable name used in constructor argument and 
// property name, so can simply exclude property definition
class Point(var x: Float, var y: Float) {
}


class Point(var x: Float, var y: Float) {
  override fun toString = "($x, $y)"
}

Getters and setters:

// Within a class block

val computedProperty: Int
  get() {
    return ...
  }

var name: String
  set(value) {
    println("Name changed from '$field' to '$value'")
    field = value
    // if `name` is used instead of `field`, it would cause an infinite loop
  }

Lambdas:

{ param1: Type, param2: Type -> 
  body
}

// If lambda is the last parameter, Swift-like syntax to put it outside the braces:

intArrayOf(3, 1, 4, 1).forEach { x -> println(x) }