2017-04-06 41 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。