Scala 有没有一种方法可以通过一个HList定义多个隐式证据?
我有一段代码,在概念上类似于以下代码:Scala 有没有一种方法可以通过一个HList定义多个隐式证据?,scala,implicit,shapeless,Scala,Implicit,Shapeless,我有一段代码,在概念上类似于以下代码: //library code trait Support[K, V] def partialHandler[K, V](key: K, value: V)(implicit ev: Support[K, V]) = ??? //user code implicit val intIntSupport = new Support[Int, Int] {} implicit val intStringSupport = new Support[Int, S
//library code
trait Support[K, V]
def partialHandler[K, V](key: K, value: V)(implicit ev: Support[K, V]) = ???
//user code
implicit val intIntSupport = new Support[Int, Int] {}
implicit val intStringSupport = new Support[Int, String] {}
...
partialHandler(1, "foo)
partialHandler(1, 1)
我想知道是否有一种方法可以让此库的用户更优雅地定义支持的(K,V)
类型,例如:
val supportedTypes = new Support[Int, Int] {} :: new Support[Int, String] {} :: HNil
(本质上,我正在寻找从几乎未知的HList到
支持[K,V]
的隐式转换。这看起来不可行,但可能我遗漏了一些东西。)尝试将支持的类型
隐式化
import shapeless.ops.hlist.Selector
import shapeless.{HList, HNil}
// library code
trait Support[K, V]
object Support {
implicit def mkSupport[L <: HList, K, V](implicit l: L, sel: Selector[L, Support[K, V]]): Support[K, V] = null
}
def partialHandler[K, V](key: K, value: V)(implicit ev: Support[K, V]) = ???
//user code
implicit val supportedTypes = new Support[Int, Int] {} :: new Support[Int, String] {} :: new Support[Long, Double] {} :: HNil
partialHandler(1, "foo")
partialHandler(1, 1)
partialHandler(1L, 1.0)
// partialHandler("foo", "bar") // doesn't compile
导入shapeless.ops.hlist.Selector
导入无形状。{HList,HNil}
//库代码
特质支持[K,V]
对象支持{
隐式def mkSupport[L为了理智起见,我觉得您应该使用包装类case类支持[L@HTNW yes]