如何使用Poly函数修复此编译错误

时间:2016-09-06 17:23:30

标签: scala shapeless scala-cats

我正在尝试将HList Xor映射到HList ValidatedNel并收到错误:

scala> type Result[A] = Xor[String, A]    
defined type alias Result

scala> type Validation[A] = ValidatedNel[String, A]
defined type alias Validation

scala> val r0 = Xor.right(0)
r0: cats.data.Xor[Nothing,Int] = Right(0)

scala> val r1 = Xor.left("xxx")
r1: cats.data.Xor[String,Nothing] = Left(xxx)

scala> import shapeless._
import shapeless._

scala> val rs = r0 :: r1 :: HNil
rs: shapeless.::[cats.data.Xor[Nothing,Int],shapeless.::[cats.data.Xor[String,Nothing],shapeless.HNil]] = Right(0) :: Left(xxx) :: HNil

scala> object toValidation extends (Result ~> Validation) { def apply[T](r: Result[T]): Validation[T] = r.toValidatedNel }
defined object toValidation

scala> rs map toValidation
<console>:41: error: type mismatch;
 found   : toValidation.type
 required: shapeless.Poly
              rs map toValidation

上面的代码有什么问题以及如何修复它?

1 个答案:

答案 0 :(得分:2)

你能仔细检查一下你的进口吗?

我怀疑~>引用cats的自然转换而非shapeless的Poly。

在定义shapeless.poly._对象之前导入toValidation应该摆脱该错误。