尝试
import scala.language.experimental.macros
import scala.reflect.macros.{blackbox, contexts}
trait Exists[A]
object Exists {
implicit def materialize[A]: Exists[A] = macro impl[A]
def impl[A: c.WeakTypeTag](c: blackbox.Context): c.Tree = {
import c.universe._
val context = c.asInstanceOf[contexts.Context]
val global: context.universe.type = context.universe
val analyzer: global.analyzer.type = global.analyzer
val callsiteContext = context.callsiteTyper.context
val tpA = weakTypeOf[A]
val searchResult = analyzer.inferImplicit(
tree = EmptyTree.asInstanceOf[global.Tree],
pt = tpA.asInstanceOf[global.Type],
reportAmbiguous = false,
isView = false,
context = callsiteContext,
saveAmbiguousDivergent = true,
pos = c.enclosingPosition.asInstanceOf[global.Position]
)
val isAmbiguous = callsiteContext.reporter.firstError match {
case Some(analyzer.AmbiguousImplicitTypeError(_,_)) => true
case _ => false
}
if (searchResult.isSuccess || searchResult.isAmbiguousFailure || isAmbiguous)
q"new Exists[$tpA] {}"
else c.abort(c.enclosingPosition, s"no implicit $tpA")
}
}
测试
// no implicit Int
// implicitly[Exists[Int]] // doesn't compile
implicit val i: Int = 1
implicitly[Exists[Int]] // compiles
implicit val i: Int = 1
implicit val i1: Int = 2
implicitly[Exists[Int]] // compiles
我猜原来Search
是
trait Foo[U, V]
trait Search[L <: HList, V]
trait LowPrioritySearch {
implicit def tail[H, T <: HList, V](implicit search: Search[T, V]): Search[H :: T, V] = null
}
object Search extends LowPrioritySearch {
def apply[L <: HList, U](implicit s: Search[L, U]): U = null.asInstanceOf[U]
implicit def head[U, T <: HList, V](implicit foo: Foo[U, V]): Search[U :: T, V] = null
}
现在有了Exists
def apply[L <: HList, U](implicit ev: Exists[Foo[_, U]], s: Search[L, U]): U = null.asInstanceOf[U]
也可以
Search[L, Boolean] //compiles
// Search[L, Double] //does not compile
在 2.13.0 中测试
libraryDependencies ++= Seq(
scalaOrganization.value % "scala-reflect" % scalaVersion.value,
scalaOrganization.value % "scala-compiler" % scalaVersion.value
)