Kotlin Extensions And Pipe

Introduction

1
2
3
4
5
6
7
8
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1] // 'this' corresponds to the list
this[index1] = this[index2]
this[index2] = tmp
}

val list = mutableListOf(1, 2, 3)
list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'

Extensions

Example - Pipe

Arithmetics Version 1

1
2
3
4
5
6
7
8
9
fun multiplyByTwo(x: Int): Int = x * 2

fun addOne(x: Int): Int = x + 1

fun addTwo(x: Int) : Int = x + 2

fun performOperations(x : Int) : Int {
return multiplyByTwo(addTwo(addOne(x)))
}

Arithmetics Version 2

1
2
3
4
5
6
7
8
9
fun Int.addOne(): Int = this + 1

x.addOne()
.addTwo()
.multiplyByTwo()
// or
x.let { addOne(this) }
.let { addTwo(this) }
.let { multiplyByTwo(this) }

Arithmetics Version 3

1
2
3
infix fun <T> T.then(func: (T) -> T): T = func(this)

x then { it + 1 } then { it + 2 }

Arithmetics Version 4

1
2
3
4
5
6
7
8
9
10
11
fun <T> T.pipe(vararg functions: (T) -> T): T {
return functions.fold(this) { value, f ->
f(value)
}
}

fun main() {
val result = 100.pipe(::addOne, ::addTwo, ::multiplyByTwo)
println(result)
}
// result is 206

Reference