我想写我自己的类ErrorOr
,其中会有Some
和Failure
的情况。我需要编写自己的flatMap()
,但是在第二行弹出一个错误。我怎么修理它?
object adt:
enum ErrorOr[+V]:
/*
Two case:
a case for a regular value
a case for an error (it should contain an actual throwable)
*/
case Some(x: V) extends ErrorOr[V]
case Failure extends ErrorOr[Throwable]
/*
in case of failing the method with exception
no exception is thrown but the case for an error is returned
*/
def flatMap[Q](f: V ⇒ ErrorOr[Q]): ErrorOr[Q] =
this match
case ErrorOr.Some(v) ⇒ f(v)
case ErrorOr.Failure ⇒ ErrorOr[Q].Failure
我认为你的枚举有问题。我认为你正在尝试做一些类似于Try[T]
的事情。你可以看看Try和它的子类Success和Failure的顶部声明。
在尝试的想法。失败时,可以重写ErrorOr。失败如下:
case Failure(e : Throwable) extends ErrorOr[V]
不要忘记改变你的flatMap(f)
作为失败接受一个参数