Coding Kotlin functional style. Is it possible?


Hi, I’m trying to code Kotlin using something like a pipe operator (in elixir) and I came up with this:

fun a(int a) = a
.let { transformOne(it) }
.let { transformTwo(it) }
.let { transformThree(it}

Using normal code style this above code is equal to this:

fun a(int a): Any {
val resultOne =  transformOne(a) 
val resultTwo =  transformOne(resultOne) 
return transformThree(resultTwo) 

Coding like the first example is viable? Is bad for performance?


Depends on whether you like the way it looks.

No. let is an inline function. It should generate close to identical code to your second example. There might be some small differences but none impacting performance.

You might also be interested in this topic about the possibility of a pipe operator. Although I doubt that one will be implemented it contains some useful ideas and implementations.


Just gave a lectures on that yesterday. The orthodox Kotlin is closer to functional style than procedural (I mean the class bodies an object structures). So The first variant is preferred. Also it is possible to use method references to simplify it further.

Yet, one should remember that Kotlin is not pure functional language, therefore some things like using recursion instead of cycles is not encouraged (while possible).


I would not try to strive for superficial “elegance” through a functional programming style. Especially let doesn’t add a meaning, while an additional variable can do. Even Martin Odersky, the creator of Scala, which is way more functional than Kotlin, recommends to use variables instead of endless call chains.


I think it is a point that it is controversial issue. In most cases I agree that declaring variable is better for debug and readability, but if you really have function composition, it is better to have it functional way. We can’t discuss it without real example since the simplified example in this topic is too generic.

Kotlin encourages to use functional chains in many places, but not everywhere. I think it is great. The functional programming is good, but pure functional programs without state sometimes greatly complicate everything.