【问题标题】:Is there a way to define multiple implicit evidences via a single HList?有没有办法通过单个 HList 定义多个隐式证据?
【发布时间】:2019-11-09 13:29:26
【问题描述】:

我有一段代码,概念上类似于以下代码:

//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] 的隐式转换。这看起来不可行,但也许我遗漏了一些东西。)

【问题讨论】:

    标签: scala implicit shapeless


    【解决方案1】:

    尽量让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
    

    【讨论】:

    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多