Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xuwei-k
Created October 30, 2014 10:26
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 xuwei-k/ec8fe83a230793b2b2fc to your computer and use it in GitHub Desktop.
Save xuwei-k/ec8fe83a230793b2b2fc to your computer and use it in GitHub Desktop.
scala macros and structural subtyping
Welcome to Scala version 2.11.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_67).
Type in expressions to have them evaluated.
Type :help for more information.
scala> :paste
// Entering paste mode (ctrl-D to finish)
import scala.language.experimental.macros
import scala.reflect.macros.Context
object A {
def impl(c: Context): c.Expr[Int] = {
import c.universe._
c.Expr[Int](Literal(Constant(2)))
}
}
class A {
def x: Int = macro A.impl
}
// Exiting paste mode, now interpreting.
warning: there was one deprecation warning; re-run with -deprecation for details
import scala.language.experimental.macros
import scala.reflect.macros.Context
defined object A
defined class A
scala> val a0 = new A
a0: A = A@34aad3ab
scala> a0.x
res0: Int = 2
scala> val a1: {def x: Int} = a0
a1: AnyRef{def x: Int} = A@34aad3ab
scala> a1.x
warning: there was one feature warning; re-run with -feature for details
java.lang.NoSuchMethodException: A.x()
at java.lang.Class.getMethod(Class.java:1665)
at .reflMethod$Method1(<console>:16)
... 33 elided
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment