作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个方法取 HList
并使用它来构建类的实例。
我想提供一些简化的语法,隐藏显式的缺点。所以我想从:
MyThingy.describe( 42 :: true :: "string" :: HNil)
MyThingy.describe {
42
true
"string"
}
MyThingy
被定义为
class MyThingy[L <: HList](elems: L)
def describe[L <: HList](elements: Unit): MyThingy[L] = macro MyThingyMacros.describeImpl[L]
def describeImpl[L <: shapeless.HList : c.WeakTypeTag](c: Context)(elems: c.Tree): c.Tree = {
import c.universe._
def concatHList: PartialFunction[Tree, Tree] = {
case Block(l, _) =>
val els = l.reduceRight((x, y) => q"shapeless.::($x,$y)")
q"$els :: shapeless.HNil"
}
concatHList.lift(elems) match {
case None => c.abort(c.enclosingPosition, "BOOM!")
case Some(elemsHList) =>
val tpe = c.typecheck(elemsHList).tpe
q"new MyThingy[$tpe]($elemsHList)"
}
}
exception during macro expansion: scala.reflect.macros.TypecheckException: inferred type arguments [Int,Boolean] do not conform to method apply's type parameter bounds [H,T <: shapeless.HList]
[Int, Boolean]
从宏扩展之前的块。我也不明白为什么它需要两个参数,其中
describe
和
MyThing
只需要一个。
最佳答案
如果您可以使用逗号分隔的参数列表,那么您可以遵循 shapeless HList
中使用的样式。伴生对象 apply
方法,
scala> import shapeless._
import shapeless._
scala> object MyThingy {
| def describe[P <: Product, L <: HList](p : P)
| (implicit gen: Generic.Aux[P, L]) : L = gen.to(p)
| }
defined object MyThingy
scala> MyThingy.describe(42, true, "String")
res0: this.Repr = 42 :: true :: String :: HNil
scala> res0.head
res1: Int = 42
关于scala - 使用宏构建列表时推断 HList 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474325/
我是一名优秀的程序员,十分优秀!