3. IMPORTANT
WARNING
The reflection/macros in Scala 2.10
are experimental and pretty complex,
you might shoot yourself in the foot
or worse and be the first one to do it.
(They are also totally awesome)
5. What is reflection?
wikipedia
”... reflection is the ability of a
computer program to examine ...
and modify the structure and
behavior ... of an object at runtime.
6. But ...
Hasn’t Scala already got
the Java reflection API?!
No support for Scala constructs!
Type erasure
List[Int] + compiler = List :(
7. we want something better!
Also:
Homoiconic(ness) - express the language in itself
One API for reflection, macros (and the
compiler)
Support for reification
No overhead when not used
9. What about macros?
wikipedia
”
A macro (from the Greek μακρό for "big" or "far")
in computer science is a rule or pattern that
specifies how a certain input sequence (often a
sequence of characters) should be mapped to a
replacement input sequence (also often a sequence
of characters) according to a defined procedure.
Wat!?!
10. Ok, Iwhat is ait really?
but
Get macro,
A regular scala function
AST => AST
Called by the compiler
11. Ok,soIwhat is an AST, really?
Get it
if(1 == ”1”) { true } else { false }
if(1.==(”1”)) { true } else { false }
if(1.$eq$eq(”1”)) { true } else { false }
13. if(1.$eq$eq(”1”)) { true } else { false }
If
Expr
Expr Expr
case class If(cond: Expr,
then: Expr,
else: Expr)
14. So, We have a function
running at compile time
Transforming an
AST to a new AST
what do we do with it?
15. Ideas for of the top of my head
out
macros
Compile time checking of strings
Generic no-runtime-overhead toString
Super efficient loops
zero-overhead logger, assert
16. Ideascompile time checking of strings
for macros
def myMacro(expr: Expr): Expr {
if (expr != valid dateformat) throw Error
else expr
}
17. Ideas for macros
generic toString with zero-overhead
def toStringMacro[T](expr: Expr[T]): Expr[String] {
expr for class name of T +
each field with public getter
}
18. Time to
show some
(Awesome) macros
Finally!
e slides
listening fiv
(I stopped
ago)
Photo: Paul Lewis
19. Resourcescan I learn more?
... where
Odersky: http://channel9.msdn.com/Events/Lang-
NEXT/Lang-NEXT-2012/Reflection-and-Compilers
Scalamacros.org: http://scalamacros.org/talks/
2012-05-19-ScalaReflect.pdf
Daniel Sobral: http://dcsobral.blogspot.fr/2012/07/
json-serialization-with-reflection-in.html
20. Questions?
Slides:
topconf.com / the program page
Sample project:
http://github.com/johanandren/macros-2012
mail: johan.andren@mejsla.se
twitter: @apnylle