With trying to follow a functional approach, is it...
# arrow
k
With trying to follow a functional approach, is it frowned upon to create non-pure extension functions? I’m trying reduce code smells, and wondering if this is one.
s
What kind of non-pure are we talking about? An example would be great.
k
Taking a List<Foo> and mapping it to List<Bar> where the mapping requires some IO operations like fetching records from a database.
s
No, there is nothing that differentiates a regular function from an extension function. So following the "rules" of what is a pure function remains the same between the two. I.e.
Copy code
fun add(x: Int, y: Int): Int = x + y
fun Int.add(y: Int): Int = this + y
These functions are identical, we can even see that if we assign them using method referencing.
Copy code
val f: KFunction2<Int, Int, Int> = ::add
val g: KFunction2<Int, Int, Int> = Int::add
Exact same
KFunction
type, so using an extension function doesn't affect purity. If you access a database, then it should take
database
as a parameter or live inside an interface where the impl has access to
database
.
k
Thank you gents for taking the time to respond
c
If you use coroutines, IO is automatically explicit via the
suspend
keyword, so it is always clear whether a function is pure or not. Otherwise, do try to keep it clear in the name (impure functions should be named after actions, e.g.
sort
in the standard library which sorts in-place, vs
sorted
which returns a sorted copy).
1