所以我有以下函数定义。
def partition[A, B, C](
partitionF: A => Either[B, C])
Run Code Online (Sandbox Code Playgroud)
其中A,B和C是任意类型。
现在,我正在定义要传递的函数
sealed trait Response
case object ThisResponse extends Response
case object ThatResponse extends Response
case object ThisDirection
case object ThatDirection
def responsePartition(response: Response):
Either[ThisDirection, ThatDirection] = response match {
case ThisResponse => Left(ThisDirection)
case ThatResponse => Right(ThatDirection)
}
Run Code Online (Sandbox Code Playgroud)
然后我们将其传递如下
partition(responsePartition)
Run Code Online (Sandbox Code Playgroud)
在业务逻辑中。
现在,我试图单独获取responsePartition中定义的A => B和A => C方法
所以我要找的是
val partitionFonB : A => B = ??? // This is case of this example would be ThisResponse => ThisDirection
Run Code Online (Sandbox Code Playgroud)
和
val partitionFonC : A => C = ??? // This is case of this example would be ThatResponse => ThatDirection
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?我尝试过向右投影和向左投影,但是我无法获得正确的类型。
通常,您不能从type的函数中提取(总计)A => B或A => C函数A => Either[B, C]。如果该函数B为特定值生成一个a1,A => C则不会在此处定义该函数,反之亦然。
如果您所拥有的A => Either[B, C]只是A => Option[B]and A => Option[C](使用_.toLeft.toOptionand _.toOption),那么您将尽力而为。
对于您的特殊情况,您可以提取ThisResponse => ThisDirection和ThatResponse => ThatDirection作为单独的函数开始,然后将它们组合以获得一个Response => Either[ThisDirection, ThatDirection]函数:
def thisResponse(response: ThisResponse): ThisDirection = ThisDirection // or any This-specific functionality
def thatResponse(response: ThatResponse): ThatDirection = ThatDirection // or any That-specific functionality
def responsePartition(response: Response):
Either[ThisDirection, ThatDirection] = response match {
case r:ThisResponse => Left(thisResponse(r))
case r:ThatResponse => Right(thatResponse(r))
}
Run Code Online (Sandbox Code Playgroud)