https://kotlinlang.org logo
#arrow
Title
# arrow
k

Kev

03/18/2024, 9:04 AM
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

Sam

03/18/2024, 9:10 AM
What kind of non-pure are we talking about? An example would be great.
k

Kev

03/18/2024, 9:36 AM
Taking a List<Foo> and mapping it to List<Bar> where the mapping requires some IO operations like fetching records from a database.
s

simon.vergauwen

03/18/2024, 9:48 AM
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

Kev

03/18/2024, 1:25 PM
Thank you gents for taking the time to respond
c

CLOVIS

03/18/2024, 1:32 PM
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