Skip to content

Instantly share code, notes, and snippets.

@nishanthvijayan
Last active April 30, 2023 12:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nishanthvijayan/9d15f8cbe8db0996562ec94163d5d21d to your computer and use it in GitHub Desktop.
Save nishanthvijayan/9d15f8cbe8db0996562ec94163d5d21d to your computer and use it in GitHub Desktop.
Simple Pipe forward operator in Kotlin
infix fun<R,S,T> ((R) -> S).andThen(f : ((S) -> T)): ((R) -> T) = { f(this(it)) }
val toUpperCase = { x: String -> x.toUpperCase()}
val exclaim = { x: String -> x + "!"}
val reverse = {r: List<String> -> r.asReversed() }
val head = { l: List<String> -> l[0]}
val shout = exclaim andThen toUpperCase
val last = reverse andThen head
val shoutLast = reverse andThen head andThen exclaim andThen toUpperCase
fun main(args: Array<String>){
println(
shoutLast(listOf("First", "Second", "Third", "Last"))
)
// prints LAST!
}

Here I try to implement a simple pipe forward operator similar to |> operator in Elixir or the andThen operator in Scala

Let's say you have a need for doing something like this

val x = f("something")
val y = g(x)
val z = h(y)

This is also equivalent to saying:

val z = h(g(f("something"))) // Ugly

You can rewrite the above like this:

val z = (f andThen g andThen h)("something") // Better

OR if you want to reuse the composed function again:

// Much Better
val newFunc = f andThen g andThen h
val z = newFunc("something")
val a = newFunc("else)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment