Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created August 10, 2014 13:11
Show Gist options
  • Save milessabin/61860a59a93184c0c5df to your computer and use it in GitHub Desktop.
Save milessabin/61860a59a93184c0c5df to your computer and use it in GitHub Desktop.
A better implicitly ... trick for generating a stable identifier due to @xeno_by and @den_sh
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
@martin-g
Copy link

Where the values for U (23 and true) came from ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment