Kotlin

Hello

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

val & var

val s1 = 1
s2 = 2  // Error

var s2 = 1
s2 += 1

Nulls

var s1: Int? = 1
s1 = null

var s2: Int = 1
s2 = null // Error!

Arguments

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

fun main() {
    print(sum(2, 2))

    print(sum(2))

    print(sum(a = 2, b = 2))
}

Expressions

fun main() {
    val name = "Andy"
    val ret = if (name == "Andy") "yes" else "no"
    print("$ret")
}

Expressions

fun main() {
  val result = try {
        readLine()
    } catch (e: Exception) {
        "Oops..."
    }
  print("Result: ${result}")
}

Loops

for (item in collection) print(item) ...

for (i in 1..3) ...

for (i in 6 downTo 0 step 2) ...

for ((index, value) in array.withIndex()) ...

while (x > 0) ...

do ... while(x > 0)

Lambdas

fun wrapGreeting(block: () -> String) {
    print("Hello ${block()}!!!")
}

fun main() {
    wrapGreeting {
        "Andy"
    }
}

Lambdas

fun wrapGreeting(block: () -> String) {
    print("Hello ${block()}!!!")
}

fun main() {
    wrapGreeting {
        readLine()!!
    }
}
Hello Andy!!!

Lambdas

import java.io.FileWriter

fun main() {
    FileWriter("myfile.txt").use { file ->
        file.write("Hello!!!")
    }
}

Classes

class Empty

class Person(val lastName: String,
             val firstName: String,
             val age: Int)

Classes

class Device {
  private val serial: String

  constructor(serial: String) {
      this.serial = serial
  }

  init {
      // Default constructor initializer
  }

  fun getInfo(): String {
      return "My serial: $serial"
  }
}

Classes

class Device2(private val serial: String) {
  fun getInfo() = "My serial: $serial"
}

Apply & Use

class Person(val name: String) {
  lateinit var email: String
}

fun main() {
  Person(name = "Bob").apply {
    email = "bob@bobby.me"
  }
}

Apply & Use

fun main() {
  Person(name = "Bob").use {
    it.email = "bob@bobby.me"
  }
}

Extensions

fun Person2.asJson(): String = """
    {
      "name": ${name},
      "email": ${email}
    }
"""

val bob = Person("Bob")
print(bob.asJson())