scala macros

Download Scala Macros

Post on 30-Oct-2014




1 download

Embed Size (px)


JavaZone 2013 Scala Macros


1. SCALA MACROS Adam Warski, JavaZone 2013 @adamwarski 2. @adamwarski ATTEND THIS TALK IF you are curious what a macro is you are wondering how to write a macro in Scala you have not yet decided if you love or hate macros youd like to know if they are used anywhere 3. @adamwarski WHAT IS A MACRO? Macro (large): expands into something larger Function: code => code! Invoked at build/compile-time 4. @adamwarski SCALA MACROS Written in Scala Have access to and can manipulate the AST Use compiler/reflection APIs Type-safe 5. @adamwarski MACROS IN OTHER LANGUAGES C/C++ preprocessor #define BUFFER_SIZE 1024 #define min(X, Y) ((X) < (Y) ? (X) : (Y)) Lisp/Clojure, Racket (Scheme) code is data (list) quoting Since macros are so much harder to use than functions, a good rule of thumb is: don't use defmacro if defun will work fine from 6. @adamwarski MOTIVATION TO ADD MACROS TO SCALA (its not a lean language already!) Remove boilerplate Replace run-time reflection Generate type-checked code Deep embedding of DSLs Type-check external DSLs Simplify compiler in the long run 7. @adamwarski REACTIONS TO MACROS Mixed ;) 8. @adamwarski PLAN FOR THE NEXT 50 MINUTES 1. How to write a simple macro 2. Where macros are used now? 3. Upcoming new types of macros 9. @adamwarski ABOUT ME During the day: coding @ SoftwareMill SoftwareMill: a great software house! Afternoon: playgrounds, Duplo, etc. Evening: blogging, open-source Original author of Hibernate Envers ElasticMQ, Veripacks, MacWire 10. @adamwarski DEF MACROS Available since Scala 2.10 (Jan 2013) Only one type of many possible macro types Experimental status But they will stay ;) 11. @adamwarski WRITING A MACRO STEP-BY-STEP Goal transform this: debug(x*amount) To: println("x*amount = " + (x*amount)) So that it outputs: x*amount = 10.23 12. DEMO WRITING A SIMPLE MACRO 13. @adamwarski WHERE ARE MACROS USED? Slick Akka Async Expecty MacWire examples are mostly from the projects websites 14. @adamwarski SLICK @table(name="COFFEES") case class Coffee( @column(name="NAME") name: String, @column(name="PRICE") price: Double ) val q = Queryable[Coffee] val r = q.filter(_.price > 3.0).map( 15. @adamwarski ASYNC val f1 = Future { beSlow(); 19 } val f2 = Future { beSlow(); 23 } val futureResult = for { v1 responsibility 32. @adamwarski LINKS macros-a-short-tutorial/ 33. @adamwarski COME & GET A STICKER Adam Warski @adamwarski