Pipelines in Kotlin (first steps)

published Dec 03, 2017 10:20   by admin ( last modified Dec 03, 2017 10:27 )

I cannot lie, I like pipelines. They make a program easy to understand, and you get functional programming for free. And parallelization. So how do you do it in Kotlin? In Javascript I use the Bluebird library, which has some extra goodies too. But since I am now looking into Kotlin, what's the deal there?

Java itself now has streams, but Kotlin's support for pipelines predate Java's. Many types can be pipelined in Kotlin, but in Java they need to converted to streams. Kotlin's pipelines are eager, unless you convert them to sequences, in which case they match the lazy evaluation of Java streams. Here is a Kotlin program that seems to work:

package se.webworks.pipes

fun main(args: Array<String>) {
    val myList = listOf("a1", "a2", "b1", "c2", "c1")

    myList
            .filter({ s -> s.startsWith("c") })
            .map( { emBiggen(it) })
            .sorted()
            .forEach({s-> println(s) })
}

fun emBiggen(thing: String): String{

    return thing.toUpperCase()
}

 

"it" is the default variable where things end up if you do not specify. I like that. Very Hypertalk-y.

I learnt it all here http://www.baeldung.com/java-8-stream-vs-kotlin.

What I am wondering now, is if you can curry functions, so that you can pre-configure them with some parameters already in the pipeline. Maybe just removing the brackets and have a function return a function will do the trick?

We will see…

Why pipelines then? As Walther Bright, creator of the D language wrote:

With these thoughts in mind, I look back at all my failures at reusable code and notice something else: It looks nothing at all like: source → algorithm → sink. In fact, it looks like a bunch of nested loops. The source data enters at the top, and gets swirled around and around in ever smaller and tighter loops, and leaves via the sink in the center of that maelstrom.

Read more: Link - Component Programming in D | Dr Dobb's