【发布时间】:2022-07-29 19:32:48
【问题描述】:
根据docs,我应该用一个对象来实现一个效果。
fun interface JustEffect<A> : Effect<Just<A>> {
suspend fun <B> Just<B>.bind(): B = value
}
object effect {
operator fun <A> invoke(func: suspend JustEffect<*>.() -> A): Just<A> =
Effect.restricted(eff = { JustEffect { it } }, f = func, just = { Just(it) })
}
这是本教程的一般指南。我很好奇是否有人知道他们为什么使用对象?我的具体用例如下:
我们已经有一个包装器对象,称为PoseidonRes,它可以是成功或错误。我们普遍使用它,并且不想到处切换到 Either 类型。话虽如此,这是我的自定义效果,以及我是如何实现的。
fun interface PoseidonResEffect<A> : Effect<PoseidonRes<A>> {
suspend fun <T> PoseidonRes<T>.bind(): T = when (this) {
is SuccessResponse -> this.response
is ErrorResponse -> control().shift(this)
}
}
fun <A> posRes(func: suspend PoseidonResEffect<A>.() -> PoseidonRes<A>): PoseidonRes<A> =
Effect.restricted(
eff = { PoseidonResEffect { it } },
f = func,
just = { it }
)
主要区别在于,我将函数接口实现为函数,而不是调用对象。我真的很想知道为什么推荐一种方式,而这看起来非常好。我已经挖掘了文档,但找不到答案。如果它实际上在文档中,请 RTFM 我。
在呼叫站点看起来像
posRes {
val myThing1 = thingThatsPoseidonResYielding().bind()
val myThing2 = thingThatsPosiedonResYielding2().bind
SuccessResponse(order.from(myThing1, myThing2))
}
这两种实现看起来都一样。测试通过任何一种方式。这是怎么回事?
【问题讨论】:
标签: android kotlin functional-programming monads arrow-kt