Is there a way to define multiple implicit evidences via a single HList?

Deadly 提交于 2020-05-13 19:02:26

问题


I have a piece of code, conceptually similar to the following one:

//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)

I wonder if there is a way to let users of this library define supported (K, V) types more elegantly, e.g.:

val supportedTypes = new Support[Int, Int] {} :: new Support[Int, String] {} :: HNil

(In essence, I'm looking for an implicit conversion from pretty much unknown HList to Support[K, V]. This doesn't look doable, but maybe I'm missing something.)


回答1:


Try to make supportedTypes implicit

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


来源:https://stackoverflow.com/questions/58779756/is-there-a-way-to-define-multiple-implicit-evidences-via-a-single-hlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!