我有一些专门的类,我想使用Kotlin和Arrow创建,它们将围绕Arrow或monad。我创建了以下代码来使用Kotlin的委托,但我想知道它是否可以简化或使其更地道。如有任何建议,我们将不胜感激。
感谢您的时间和兴趣。
internal data class EitherWrapper<L,R>(private var delegate: Either<L,R>) {
internal operator fun getValue(thisRef: Any?, property: KProperty<*>): Either<L,R> {
return delegate
}
internal operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Either<L,R>) {
delegate = value
}
}
fun main(args: Array<String>) {
val delegate: Either<Exception, String> = Right("howdy")
val myeither: Either<Exception, String> by EitherWrapper(delegate)
println("IsLeft(): ${myeither.isLeft()}")
println("IsRight(): ${myeither.isRight()}")
}发布于 2020-07-30 21:52:56
你的代码是正确的,就我所见,你能做的唯一的改进就是使它泛型,而不是特定的,如下所示:
internal data class DelegateWrapper<T>(private var delegate: T) {
internal operator fun getValue(thisRef: Any?, property: KProperty<*>): T =
delegate
internal operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
delegate = value
}
}发布于 2020-07-31 09:28:02
所以,我想我对我的问题有了一个解决方案。下面的代码将an包装在一个新类型中: Exceptional。这段代码是我想要构建的内容的起点。最终,我将拥有如下内容:

我可以在后端服务中传递此类型的实例,并返回更精确的异常、错误或值。
interface EitherMonad<L, R> {
val either: Either<L, R>
}
class BaseEitherMonad<L, R>(
override val either: Either<L, R>
) : EitherMonad<L, R>
class Exceptional<R>(
private val delegate: EitherMonad<Exception, R>
) : EitherMonad<Exception, R> by delegate {}
fun main() {
val delegateRight = BaseEitherMonad<Exception, String>(Either.Right("howdy"))
val exceptionalRight = Exceptional(delegateRight)
println("IsLeft(): ${exceptionalRight.either.isLeft()}")
println("IsRight(): ${exceptionalRight.either.isRight()}")
exceptionalRight.either.fold({ throw it }, { println("Right: $it") })
exceptionalRight.either.map { println(it) }
val delegateLeft = BaseEitherMonad<Exception, String>(Either.Left(IllegalStateException("Boom!")))
val exceptionalLeft = Exceptional(delegateLeft)
println("IsLeft(): ${exceptionalLeft.either.isLeft()}")
println("IsRight(): ${exceptionalLeft.either.isRight()}")
exceptionalLeft.either.fold({ throw it }, { println("Right: $it") })
exceptionalLeft.either.map { println(it) }
}一次跑步:

https://stackoverflow.com/questions/63165542
复制相似问题