Skip to content

Instantly share code, notes, and snippets.

@aloiscochard
Last active September 11, 2016 16:39
Show Gist options
  • Save aloiscochard/552d2b83a11fb32a9aee6c3e9e47d8ff to your computer and use it in GitHub Desktop.
Save aloiscochard/552d2b83a11fb32a9aee6c3e9e47d8ff to your computer and use it in GitHub Desktop.
Fun with fun-deps in scala.
/*
object Test0 {
import scalaz.meta.Foo._
val s: String = 1024.bar
val i: Int = "test".bar
println(s) // bar
println(i) // 42
}
*/
import language.experimental.macros
import scala.reflect.macros.whitebox.Context
import scala.language.implicitConversions
object Foo {
implicit def fooOps[I, O](i: I)(implicit I: Foo[I, O]): Foo[I, O] = I
implicit def foo[I, O]: Foo[I, O] = macro FooMacros.foo[I, O]
}
class Foo[I, O] {
final def bar: O = macro FooMacros.bar[I, O]
}
object FooMacros {
def foo[I: c.WeakTypeTag, O: c.WeakTypeTag](c: Context): c.Expr[Foo[I, O]] = {
import c.universe._
val i = weakTypeOf[I]
val o = if (i =:= typeOf[String]) {
typeOf[Int]
} else {
typeOf[String]
}
c.Expr[Foo[I, O]](q"new scalaz.meta.Foo[$i, $o]")
}
def bar[I: c.WeakTypeTag, O: c.WeakTypeTag](c: Context): c.Expr[O] = {
import c.universe._
val Apply(Apply(_, List(tree)), _) = c.prefix.tree
if (weakTypeOf[O] =:= typeOf[Int]) {
c.Expr[O](q"42")
} else {
c.Expr[O](q""""bar"""")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment