【发布时间】:2020-04-06 15:23:21
【问题描述】:
我正在尝试实现获取第一个元素的通用函数:
import shapeless.ops.hlist.IsHCons
import shapeless.{Generic, HList}
object App {
def main(args : Array[String]) {
val a: Int = getFirst((1, 2, 3))
val b: String = getFirst(("a", "b", 10, 45, "aaa"))
}
def getFirst[A, Head, Repr <: HList, Tail <: HList](input: A)
(implicit hcons: IsHCons.Aux[Repr, Head, Tail],
gen: Generic.Aux[A, Repr]): Head = gen.to(input).head
}
问题是编译器无法正确推断Repr 和Tail 并将它们设置为Nothing。就是这样:
Error:(9, 26) could not find implicit value for parameter gen: shapeless.Generic.Aux[(Int, Int, Int),Repr]
val a: Int = getFirst((1, 2, 3))
Error:(9, 26) not enough arguments for method getFirst: (implicit hcons: shapeless.ops.hlist.IsHCons.Aux[Nothing :: Nothing,Head,Tail], implicit gen: shapeless.Generic.Aux[(Int, Int, Int),Nothing :: Nothing])Head.
Unspecified value parameter gen.
val a: Int = getFirst((1, 2, 3))
Error:(10, 29) could not find implicit value for parameter gen: shapeless.Generic.Aux[(String, String, Int),Repr]
val b: String = getFirst(("a", "b", 10))
Error:(10, 29) not enough arguments for method getFirst: (implicit hcons: shapeless.ops.hlist.IsHCons.Aux[Nothing :: Nothing,Head,Tail], implicit gen: shapeless.Generic.Aux[(String, String, Int),Nothing :: Nothing])Head.
Unspecified value parameter gen.
val b: String = getFirst(("a", "b", 10))
有什么办法可以解决这个问题?以下肯定可以正常工作:
val a: Int = getFirst[(Int, Int, Int), Int, Int :: Int :: Int :: HNil, Int :: Int :: HNil]((1, 2, 3))
但是这样非常麻烦和丑陋。
【问题讨论】:
标签: scala functional-programming generic-programming shapeless type-level-computation