https://kotlinlang.org logo
Title
m

Michael Friend

04/02/2020, 2:52 PM
I’m currently dealing with adding side effects in a non arrow project for work where i want to do a series of operations that should short circuit the function on failure but also create an analytics event. Right now i just have a ton of elvis operators with return statement which feels real risky. Is there a better, more functional way to do something like this without arrow?
fun foo(b: Bar) : Type? {
    val filtered = b.listProp.filter { // Condition } 
    if (filtered.isEmpty()) {
        // Create and post analytics event
        return null
    }

   val unique = filtered.singleOrNull() ?: run {
        // Create different analytics event
        return null
   }
    ... // More operations that each can fail and should post an analytics event

   return t
}
Most of the checks are really basically null checks which makes the majority of the function length the analytics. Moving each analytics event into a separate function would help readability a bit but i still don’t like all the required returns
r

raulraja

04/02/2020, 4:55 PM
@Michael Friend I know you said without Arrow but just out of curiosity, why is Arrow IO not an option here?
if you want to do side effects in a short circuiting way you can implement your version of Continuation for the Kotlin suspend system
suspend tracks side effects
you will have to implement the intrinsics of the std lib or use a third party library that does that like Arrow Fx or KotlinX Coroutines. The diff between the two is that Fx is lazy by default so it guarantees safe resource handling on async context etc.
m

Michael Friend

04/02/2020, 4:58 PM
This is for work and it'll be a hard sell to get my somewhat large team to adopt arrow anytime soon. I've already started planting the seeds of of functional programming though so hopefully we can eventually add arrow, until then ill be using arrow in all my personal projects
r

raulraja

04/02/2020, 4:58 PM
If you don’t need any async or concurrent work just marking all your functions as suspend and implementing startCoroutine should work
The Continuation interface let you resume suspend functions with short circuiting error or value
👍 1
those are the relevant methods you can use to start a suspend function without the kotlinx coroutines lib and without Arrow
👍 1
m

Michael Friend

04/02/2020, 5:26 PM
I'll take a look into that, thanks! Out of curiosity since I'm somewhat new to true functional programming and arrow, what would be the best way to do this with arrow?