如何在映射我的Either类型时解决这种歧义?

时间:2017-04-06 13:57:14

标签: scala functor either scala-cats

假设我有两种类型IntResultStringResult

import cats._
import cats.data._
import cats.implicits._

scala> case class MyError(msg: String)
defined class MyError

scala> type Result[A] = Either[NonEmptyList[MyError], A]
defined type alias Result

scala> type StringResult = Result[String]
defined type alias StringResult

scala> type IntResult = Result[Int]
defined type alias IntResult

现在我想使用IntResultStringResult转换为map

scala> val good1: IntResult = 10.asRight
good1: IntResult = Right(10)

scala> good1 map (_.toString)
<console>:26: error: type mismatch;
found   : good1.type (with underlying type IntResult)
required: ?{def map: ?}
Note that implicit conversions are not applicable because they are ambiguous:
both method catsSyntaxEither in trait EitherSyntax of type [A, B](eab:Either[A,B]) cats.syntax.EitherOps[A,B]
and method toFunctorOps in trait ToFunctorOps of type [F[_], A](target: F[A])(implicit tc: cats.Functor[F])cats.Functor.Ops[F,A]
are possible conversion functions from good1.type to ?{def map: ?}
   good1 map (_.toString)

如何解决这种歧义?

1 个答案:

答案 0 :(得分:1)

简单的方法是使用投影,所以你这样做:

good1.right.map(_.toString)

这不是很棒,但它确实有效。我不知道一种导入的方法,因此仿函数与这两种浓缩都没有冲突(如果你需要两者)。

当然,您可以导入cats.syntax.either._,但这不会让您获得Functor。

相关问题