【问题标题】:How to create Hlist from single element by implicit function如何通过隐式函数从单个元素创建 Hlist
【发布时间】:2018-01-06 02:43:06
【问题描述】:

我正在尝试隐式创建一个 hlist。

case class A(value: Int)

implicit def lift(single: A): A :: HNil = single :: HNil

def something[L <: HList](l: L)(implicit lUBConstraint: LUBConstraint[L, A],
                                isHCons: IsHCons[L]) = {
    println("works")
}

something(A(1) :: A(2) :: HNil) //works
something(A(1)) //not works
something(lift(A(1))) //works

something(A(1)) 不工作。但是,我使用了 intellij idea,它可以检测到 lift 适合在这里使用。

这是来自编译器的错误消息。

推断的类型参数 [Boot.A] 不符合方法的类型参数边界 [L <: shapeless.hlist something>

类型不匹配; [error] found : Boot.A [error] required: L [error] something(A(1))

找不到参数 lUBConstraint 的隐含值:shapeless.LUBConstraint[L, Boot.A] [error] something(A(1)

【问题讨论】:

  • 在什么情况下它不起作用?有错误吗?如果是这样,请提供如图所示的错误。
  • 我编辑了问题。

标签: scala shapeless


【解决方案1】:

IIRC Scala 隐式转换不会触发以满足类型限制。

您可以修改something 的定义以允许任何此类转换工作:

def something[X, L <: HList](x: X)(
  implicit asHList: X => L,
           lUBConstraint: LUBConstraint[L, A],
           isHCons: IsHCons[L]
) = {
    println("works")
}

对于单个参数,这将使用您的 lift 函数,并使用来自 Predef&lt;:&lt; 用于实际 HLists

【讨论】:

  • 谢谢,但它对某些东西有用吗(A(1) :: A(2) :: HNil) ?
  • @Korkor 是的,就像我说的,它将使用&lt;:&lt; 代替asHList 来代替asHList
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 2018-11-03
  • 2015-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多