我有一段代码,在概念上类似于以下代码:
//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 到Support[K, V]
。这看起来不可行,但也许我错过了一些东西。)
尝试制作supportedTypes
隐含的
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)