问题
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