idea
Kotlin is a language that compiles to the JVM invented by Jetbrains.
It features a lot of sugar to make things more elegant.
classes
Declare a class with two properties a and b:
class something(val a: string, val b: string)
data classes
classes don't have statics.
object are static classes
Functions can be attached to existing classes as extension functions
fun String.getFirstWord(separator: String = " "): String {
// ...
}
Same for properties.
sealed classes are abstract classes where all the subtypes are known and declared in the same file.
delegate properties
lazy properties allows initializer on first access.
val something:string by lazy {
SomeCalculation()
}
lazy is a library function. Right of the by can be any initializer library.
functions
Kotlin supports top-level functions, including overloads of the same function and default values, typescript style.
Functions can be local as well, this supports closure.
lambda
Lambda are declared thusly:
var plusOne = list.map { number -> number + 1}
Kotlin supports lambda for traversing enumberables
fun doSomething(element: Element) {
}
list.forEach(::doSomething)
it allows easier function declaration
even = list.filter { it % 2 == 0 }
inline functions optimize and remove the lambdas away by copying the code rather than creating a lambda objects.
flow control
Switch/case is when / else
when (something) {
1 -> functionForOne()
2 -> functionForTwo()
else -> functionForElse()
}
if and many other things are values.
val x = if (something) {
println("youpi")
1
} else {
2
}
val y = when (something) {
1 -> "youpi"
2 -> "bla"
else -> "default"
}
other sugar
with allows to access object properties as local variables
with (obj) {
println("obj.a" = a)
println("obj.a = $a, b = $b")
}
to allows creation of a Pair
val map = mapOf(
"a" to 1,
"b" to 2
)
println(map["a"])
for((key, value) in map.entries) {
println("$key -> $value")
}
?. is conditional accessor
?: is a default val s = something ?: null. The right end can be any expression, including a return.
Async, callback, ...
Corountines are similar to async tasks / promises in js.
cont -> doSometing (result -> cont.resume(result))
val sequence = buildSequence {
var a = 1
while (true) {
yield (a++)
}
}
sequence.take(20).toList()
links
Kotlin has some familiarities with Typescript
references
- How to kotlin is a video with some nice sugar for kotlin