Composing functions in Kotlin with extensions and operators

fun same(val: Int) = val
fun twice(val: Int) = val * 2
fun trice(val: Int) = val * 3
fun composed(val: Int) = same(twice(trice(int)))

Extensions

fun Int.double() {
return this * 2
}
2.double() == 4
fun (() -> Unit).andHello() {
this()
println("Hello, world!")
}
fun greet() {
println("Hey there!")
}
fun greetAndHello() {
::greet.andHello()
}

Operator overloading

val map = mapOf("a" to 1, "b" to 2, "c" to 3)println(map["a"]) // 1
class Map<Key, Value> {
operator get(key: Key): Value {
// get and return the value from the map here
}
}
fun composed(val: Int) = (::trice..::twice..::same) (val)
operator fun <T, R, V> ((T) -> R).rangeTo(other: (R) -> V): ((T) -> V) {
return {
other(this(it))
}
}
fun composed(val: Int) = (::trice..::twice..::same) (val)

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daniele Conti

Daniele Conti

More from Medium

Dagger 2 Dependency Injection Part 1

Import AOSP framework jar file

Room Database Migration in Kotlin

Implement Huawei AppGallery Remote Configuration in your Xamarin Android app