Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/e489e960f7e565f592ed to your computer and use it in GitHub Desktop.
Save travisbrown/e489e960f7e565f592ed to your computer and use it in GitHub Desktop.
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.language.dynamics
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
object implicitly extends Dynamic {
def apply[T](implicit t: T): T {} = t
def selectDynamic(tpeTree: String): Any = macro implicitlyImpl
def implicitlyImpl(c: whitebox.Context)(tpeTree: c.Tree): c.Tree = {
import c.universe._
import internal._, decorators._
val q"${tpeString: String}" = tpeTree
val parsed = c.parse("null : "+tpeString)
val tpe = c.typecheck(parsed, mode = c.TYPEmode).tpe
val inferred = c.inferImplicitValue(tpe)
Literal(Constant(null)).setType(inferred.tpe)
}
}
// Exiting paste mode, now interpreting.
import scala.language.dynamics
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
defined object implicitly
scala> :paste
// Entering paste mode (ctrl-D to finish)
trait Foo[T] { type U }
implicit def fooSI: Foo[String] { type U = Int } = new Foo[String] { type U = Int }
implicit def fooDB: Foo[Double] { type U = Boolean } = new Foo[Double] { type U = Boolean }
// Exiting paste mode, now interpreting.
defined trait Foo
fooSI: Foo[String]{type U = Int}
fooDB: Foo[Double]{type U = Boolean}
scala> implicitly[Foo[String]] // Summon values, as usual
res0: Foo[String] = $anon$1@357dc417
scala> implicitly[Foo[Double]] // Summon values, as usual
res1: Foo[Double] = $anon$2@4f9b02ed
scala> val i: implicitly.`Foo[String]`.U = 23 // But it's also a stable prefix for a type
i: Int = 23
scala> val b: implicitly.`Foo[Double]`.U = true // But it's also a stable prefix for a type
b: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment