What we missed
Getter/setter
var stringRepresentation: String
get() = this.toString()
set(value) {
setDataFromString(value) // parses the string and assigns values to other properties
}
Pattern matching
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
Iterate over a range (steps, bound inclusive/exclusive)
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
Lazy properties
val p: String by lazy {
// compute the string
}
List/Map access
println(map["key"])
map["key"] = value
println(list[0])
list[0] = value
Try/Catch expression
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
Sealed / Enum class
Generics
class Box<T>(t: T) {
var value = t
}
val box: Box<Int> = Box<Int>(1)
Delegation
interface Base {
fun printMessage()
fun printMessageLine()
}
class BaseImpl(val x: Int) : Base {
override fun printMessage() { print(x) }
override fun printMessageLine() { println(x) }
}
class Derived(b: Base) : Base by b {
override fun printMessage() { print("abc") }
}
Inheritance/overriding
Operator overloading
data class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y)
val point = Point(10, 20)
fun main() {
println(-point) // prints "Point(x=-10, y=-20)"
}
Builder and DSL
fun result() =
html {
head {
title {+"XML encoding with Kotlin"}
}
body {
h1 {+"XML encoding with Kotlin"}
p {+"this format can be used as an alternative markup to XML"}
// an element with attributes and text content
a(href = "https://kotlinlang.org") {+"Kotlin"}
// mixed content
p {
+"This is some"
b {+"mixed"}
+"text. For more see the"
a(href = "https://kotlinlang.org") {+"Kotlin"}
+"project"
}
p {+"some text"}
// content generated by
p {
for (arg in args)
+arg
}
}
}
// how it works
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}