2017-04-06 69 views
1

假设我有两种类型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 

现在我想用map转换IntResultStringResult

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

上面的代码在Scala 2.12.0中正常工作(你的错误发生在2.11.8),是否升级你的Scala选项? –

+0

是的,它可能是一个选项。 – Michael

+0

刚刚遇到与猫'任一仿函数实例完全相同的问题。升级Scala对我来说不是一种选择。 – Matthias

回答

1

简单的方法是使用预测,所以你做的:

good1.right.map(_.toString) 

这不是真棒,但它的工作原理。我不知道一种导入方式,以便函子不会与任何一种浓缩(如果您同时需要)相冲突。

当然,你可以只导入cats.syntax.either._但这不会让你的Functor。