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

Lukasz Kalnik

06/30/2022, 9:21 AM
Can I build, using Arrow, a custom, generic sum type similar to
Either
but with more subtypes? I need something like this:
Copy code
sealed class DataState<T> {

    class Loading<T> : DataState<T>()

    data class Error<T>(val error: CallError) : DataState<T>()

    data class DataLoaded<T>(
        val data: T
    ) : DataState<T>()
}
And I want only the
DataLoaded
subtype to behave as
Either.Right
(e.g. when using
flatMap()
) and all other subtypes behave as
Either.Left
, i.e. having early returns from
flatMap()
. I especially would like to have the monad comprehension syntax analogous to the
either {}
DSL (using
.bind()
).
Currently when doing something with
data
I have to typecheck / cast everytime, which doesn't look elegant:
Copy code
fun workWithData() {
    val dataLoaded = (dataState as? DataLoaded) ?: return
    val data = dataLoaded.data
}
y

Youssef Shoaib [MOD]

06/30/2022, 9:32 AM
You can have the Left-y states have a common supertype, and then just use Either normally with Left being the supertype and Right being
DataLoaded
☝️ 2
l

Lukasz Kalnik

06/30/2022, 9:36 AM
Thanks, that's a brilliant solution! I will try it out 🙏
s

simon.vergauwen

06/30/2022, 9:51 AM
Here is an example @Lukasz Kalnik, https://github.com/nomisRev/ktor-arrow-example/blob/main/src/main/kotlin/io/github/nomisrev/DomainError.kt I use
sealed interface
to define "layers", and then I can unite them with a common parent to closer they come to my API edge.
l

Lukasz Kalnik

06/30/2022, 12:04 PM
Thank you for the examples!
7 Views