The beautiness of Kotlin - Episode 0

I like very much the fluency which you can define a micro-DSL with when you’re lucky enough to write Kotlin code: e.g., let’s implement a very very simple DSL to express distances:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
fun main() {
val marathon = 42.km + 195.m + 30.cm
println("Marathon = ${marathon}")
}

// Extension properties: Java/C# developer, can you exploit any similar feature? ;-)
val Int.km: Distance
get() = Distance(this.toDouble() * 1000)

val Int.m: Distance
get() = Distance(this.toDouble())

val Int.cm: Distance
get() = Distance(this.toDouble() / 100)

data class Distance(val m: Double) {
// Operator overloading made simple and OO-friendly:
// nothing to do with C# similar, static-method based feature!
operator fun plus(that: Distance) = Distance(this.m + that.m)
}

You can run the previous code here.