albertosh
02/01/2021, 9:54 AMalbertosh
02/01/2021, 9:54 AMprivate val db = mutableMapOf<String, Product>()
private val rng = Random(System.currentTimeMillis())
suspend fun getProductById(id: String): Either<Union<DbError, GetProductFromDbError>, Product> {
delay(100) // simulate some DB query
return when (rng.nextInt(10)) {
in (0..8) -> db[id]?.right() ?: ProductNotFoundInDb(id).left() // proper DB call
else -> DbNotResponding.left() // Simulate a DB failure
}
}
sealed class DbError
object DbNotResponding : DbError()
sealed class GetProductFromDbError(val id: String)
class ProductNotFoundInDb(id: String) : GetProductFromDbError(id)
As you can see, I’m simulating some errors to showcase the “available error handling” mechanisms of FP. The main idea is that getting a product from DB is either a result or an error (DB error such as connectivity failures or business error such as a non existing product)
However, I’m not able to use the Union
type (not found). Probably I’m missing some dependencies. I’m adding the arrow-core
, arrow-syntax
and ” `kapt`ing” arrow-meta
of version 0.12.0-SNAPSHOT
Youssef Shoaib [MOD]
02/01/2021, 11:50 AMarrow-meta-prelude
dependencyalbertosh
02/01/2021, 12:52 PMraulraja
02/01/2021, 1:01 PMfirst
second
etc you need implicit injection which is provided through Arrow metaraulraja
02/01/2021, 1:02 PMA | B | C
TLDR, runtime is there even the injection but it only works in the IR backend for the latest version of meta and would redline in your IDE until it has proper compiler plugin support.albertosh
02/01/2021, 1:11 PMalbertosh
02/01/2021, 1:26 PMwhen
scenarios such as
class C1
class C2
val union: Union2<C1, C2> = C1().first()
val a = when(union.value) {
is C1 -> "First"
is C2 -> "Second"
else -> "needed by compiler" // probably will get out once compiler plugins are released
}
val b = when(union) {
is First<C1> -> "First" // Cannot check for instance of erased type
is Second<C2> -> "Second" // Cannot check for instance of erased type
else -> "needed by compiler" // probably will get out once compiler plugins are released
}
The first approach (using union.value
) seems to work but I wonder if I’m doing something wrong in the second approach. Maybe is just that, not enough support for currently available APIs