无法映射到 HList [英] Unable to map on HList
问题描述
我试图用无形的方式解决这个问题.但是由于某种原因我无法映射 HList
.我会让代码不言自明.
I was trying to solve this problem with shapeless. However I am for some reason unable to map on the HList
. I'll let the code speak for itself.
import shapeless._
import HList._
case class Foo(a: Option[Int], b: Option[Int])
val a = Foo(Some(3), None)
val b = Foo(Some(22), Some(1))
implicit val fooIso = HListIso(Foo.apply _, Foo.unapply _)
val mapper = new (({ type O2[+A] = (Option[A], Option[A]) })#O2 ~> Option) {
def apply[A](x: (Option[A], Option[A])): Option[A] = x._1.orElse(x._2)
}
fooIso.fromHList(fooIso.toHList(a).zip(fooIso.toHList(b)).map(mapper))
错误信息是:
<console>:55: error: could not find implicit value for parameter mapper: shapeless.Mapper[java.lang.Object with shapeless.~>[[+A](Option[A], Option[A]),Option],shapeless.::[(Option[Int], Option[Int]),shapeless.::[(Option[Int], Option[Int]),shapeless.HNil]]]
fooIso.fromHList(fooIso.toHList(a).zip(fooIso.toHList(b)).map(mapper))
^
为什么映射不起作用?
推荐答案
有一个简单的解决方法:只需将函数定义为 object
而不是 val
:>
There's an easy fix: just define your function as an object
instead of a val
:
object f extends (({ type O2[+A] = (Option[A], Option[A]) })#O2 ~> Option) {
def apply[A](x: (Option[A], Option[A])): Option[A] = x._1 orElse x._2
}
(注意,我将函数命名为 f
而不是 mapper
以避免与 mapper
隐式参数混淆到 map
.)
(Note that I've named the function f
instead of mapper
to avoid confusion with the mapper
implicit argument to map
.)
我不确定我能帮助解决为什么——在某些时候我试图弄清楚为什么 val
对这种事情不起作用的细节在 Shapeless 中,我不记得我走了多远.
I'm not sure I can help with why—at some point I tried to work out the details of why val
wouldn't work for this kind of thing in Shapeless, and I don't remember how far I got.
这篇关于无法映射到 HList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!