SlideShare a Scribd company logo
SCALA MACROS
Adam Warski, JavaZone 2013
@adamwarski
@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
… you’d like to know if they are used anywhere
@adamwarski
WHAT IS A MACRO?
•  Macro (large): expands into something larger
•  Function: code => code!
•  Invoked at build/compile-time
@adamwarski
SCALA MACROS
•  Written in Scala
•  Have access to and can manipulate the AST
•  Use compiler/reflection APIs
•  Type-safe
@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 http://www.apl.jhu.edu/~hall/Lisp-Notes/Macros.html
@adamwarski
MOTIVATION TO ADD
MACROS TO SCALA
(it’s 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
@adamwarski
REACTIONS TO MACROS
Mixed ;)
@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
@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
http://www.warski.org
@adamwarski
“DEF” MACROS
•  Available since Scala 2.10 (Jan 2013)
•  Only one type of many possible macro types
•  Experimental status
•  But they will stay ;)
@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
DEMO
WRITING A SIMPLE MACRO
@adamwarski
WHERE ARE MACROS
USED?
•  Slick
•  Akka
•  Async
•  Expecty
•  MacWire
examples are mostly from the projects’ websites
@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(_.name)
@adamwarski
ASYNC
val f1 = Future { beSlow(); 19 }
val f2 = Future { beSlow(); 23 }
val futureResult = for {
v1 <- f1
v2 <- f2
} yield v1 + v2
@adamwarski
ASYNC
val futureResult = async {
val f1 = async { beSlow(); 19 }
val f2 = async { beSlow(); 23 }
await(f1) + await(f2)
}
@adamwarski
ASYNC
val future = async {
val f1 = async { beSlow(); true }
val f2 = async { beSlow(); 42 }
if (await(f1)) await(f2) else 0
}
•  Also possible with Akka Dataflow & CPS (but that’s so ’09)
•  Can also use for-comprehensions; but quickly gets tricky
@adamwarski
ERRORS
•  Cryptic errors?
•  Can be, if generated code doesn’t compile
•  But we can provide user-friendly errors
context.error(
c.enclosingPosition,
"You can’t do that")
DEMO
EXPECTY & MACWIRE
@adamwarski
AND OTHERS!
•  Akka 2.2 typed channels
•  ScalaMock
•  Typesafe Logging
•  …
@adamwarski
OTHER TYPES OF
MACROS
•  Coming in Scala 2.11+
•  Some also available as a compiler plugin in 2.10
based on the examples from http://scalamacros.org/
@adamwarski
DEF MACROS
•  What we’ve seen so far
•  Look like a method invocation
•  Generate code basing on:
•  The parameters
•  Enclosing method/class
•  Implicit lookups
@adamwarski
IMPLICIT MACROS
•  Useful for Type Classes
•  Available in Scala 2.10.2!
trait Showable[T] { def show(x: T): String }
def useShow[T](x: T)(implicit s: Showable[T]) =
s.show(x)
implicit object IntShowable {
def show(x: Int) = x.toString }
@adamwarski
IMPLICIT MACROS
We want to provide a “default implementation” for a type
trait Showable[T] { def show(x: T): String }
object Showable {
implicit def materialize [T]: Showable[T] =
macro ...
}
We can get access to T at compile-time and generate what’s
needed
@adamwarski
IMPLICIT MACROS
Works well with implicit search order
•  Current scope is first
•  Implicits in scope
•  Imported implicits
•  Then associated types:
•  Companion objects
•  Implicit scope of argument’s type
•  Implicit scope of type arguments
@adamwarski
MACRO ANNOTATIONS
Annotation-drive macros
•  Any definitions can be annotated
class identity extends StaticAnnotation {
def macroTransform(annottees: Any*) = macro ???
}
@adamwarski
MACRO ANNOTATIONS
•  Annottees is:
•  Annotated class + companion object
•  Method parameter, owner, companion
•  Can expand classes
•  Can create companion objects
@adamwarski
QUASIQUOTES
•  Similar to string interpolators
•  Extract from trees:
val q"def $name[..$tparams](...$vparamss): $tpt
= $body” = methodTree
•  Pattern match
tree match {
case q"def $name[..$tps](...$vps): $tpt
= $body” =>
}
@adamwarski
QUASIQUOTES
Construct
•  Terms: q"future{ $body }"
•  Types: tq"Future[$t]"
•  Cases: cq"x => x"
•  Patterns: pq"xs @ (hd :: tl)"
@adamwarski
POTENTIAL
PROBLEMS
•  Hard to write
•  Code may be harder to understand
•  And to debug
@adamwarski
WHEN TO WRITE A
MACRO?
•  Always think it through
•  Lots of repeated, boilerplate code
•  Unavoidable copy-paste (patterns)
•  Library code
macro: power => responsibility
@adamwarski
LINKS
•  http://www.warski.org/blog/2012/12/starting-with-scala-
macros-a-short-tutorial/
•  http://scalamacros.org/
•  http://slick.typesafe.com/
•  https://github.com/scala/async
•  https://github.com/adamw/macwire
•  https://github.com/adamw/scala-macro-tutorial
@adamwarski
http://codebrag.com
COME & GET A STICKER
Adam Warski @adamwarski

More Related Content

What's hot (20)

PDF
camel-scala.pdf
Hiroshi Ono
 
PPTX
es6
Imran shaikh
 
PDF
Model with actors and implement with Akka
Ngoc Dao
 
PDF
Introduction to Scala
Saleem Ansari
 
PDF
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
PPT
AS3Commons Introduction
Christophe Herreman
 
PPTX
TypeScript
Oswald Campesato
 
PPTX
Scala Refactoring for Fun and Profit
Tomer Gabel
 
PPTX
Actor-based concurrency and Akka Fundamentals
Ngoc Dao
 
KEY
The Why and How of Scala at Twitter
Alex Payne
 
PPTX
Introduction to Scala
Rahul Jain
 
PDF
User defined-functions-cassandra-summit-eu-2014
Robert Stupp
 
PDF
Useful and Practical Functionalities in Realm
Yusuke Kita
 
PDF
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
PDF
Advanced realm in swift
Yusuke Kita
 
PDF
Introduction to Scala : Clueda
Andreas Neumann
 
PPTX
002. Introducere in type script
Dmitrii Stoian
 
PPTX
A Brief Intro to Scala
Tim Underwood
 
PPT
Javascript Basics
Vishal Mittal
 
PDF
Elm kyivfprog 2015
Alexander Mostovenko
 
camel-scala.pdf
Hiroshi Ono
 
Model with actors and implement with Akka
Ngoc Dao
 
Introduction to Scala
Saleem Ansari
 
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
AS3Commons Introduction
Christophe Herreman
 
TypeScript
Oswald Campesato
 
Scala Refactoring for Fun and Profit
Tomer Gabel
 
Actor-based concurrency and Akka Fundamentals
Ngoc Dao
 
The Why and How of Scala at Twitter
Alex Payne
 
Introduction to Scala
Rahul Jain
 
User defined-functions-cassandra-summit-eu-2014
Robert Stupp
 
Useful and Practical Functionalities in Realm
Yusuke Kita
 
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Advanced realm in swift
Yusuke Kita
 
Introduction to Scala : Clueda
Andreas Neumann
 
002. Introducere in type script
Dmitrii Stoian
 
A Brief Intro to Scala
Tim Underwood
 
Javascript Basics
Vishal Mittal
 
Elm kyivfprog 2015
Alexander Mostovenko
 

Similar to Scala Macros (20)

PDF
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
scalaconfjp
 
PDF
Scala Macros
Knoldus Inc.
 
PPTX
Scalaマクロ入門 bizr20170217
dcubeio
 
PDF
Mixfix & adjectives using Scala macros
Nadav Wiener
 
PDF
Macro in Scala
takezoe
 
ODP
Introduction to Scala Macros
Knoldus Inc.
 
PDF
Eugene Burmako
Volha Banadyseva
 
ODP
Drilling the Async Library
Knoldus Inc.
 
PDF
Evolution of Macros
Osvaldas Grigas
 
PPTX
Scala 3 Is Coming: Martin Odersky Shares What To Know
Lightbend
 
PDF
Functional Scala 2020
Alexander Ioffe
 
PDF
Macro-processor
Temesgen Molla
 
PDF
Unit 2
pm_ghate
 
PDF
Handout#05
Sunita Milind Dol
 
PPTX
SPOS UNIT 2 MACRO NOTES SPOS UNIT 2 MACRO NOTESSPOS UNIT 2 MACRO NOTESSPOS...
22510707dypit
 
PDF
Scala - core features
Łukasz Wójcik
 
PDF
Short intro to scala and the play framework
Felipe
 
PDF
Macros and reflection in scala 2.10
Johan Andrén
 
PPTX
1614745770521_vivek macros.pptx
VivekSaini87
 
PDF
The Spark Big Data Analytics Platform
Amir Payberah
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
scalaconfjp
 
Scala Macros
Knoldus Inc.
 
Scalaマクロ入門 bizr20170217
dcubeio
 
Mixfix & adjectives using Scala macros
Nadav Wiener
 
Macro in Scala
takezoe
 
Introduction to Scala Macros
Knoldus Inc.
 
Eugene Burmako
Volha Banadyseva
 
Drilling the Async Library
Knoldus Inc.
 
Evolution of Macros
Osvaldas Grigas
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Lightbend
 
Functional Scala 2020
Alexander Ioffe
 
Macro-processor
Temesgen Molla
 
Unit 2
pm_ghate
 
Handout#05
Sunita Milind Dol
 
SPOS UNIT 2 MACRO NOTES SPOS UNIT 2 MACRO NOTESSPOS UNIT 2 MACRO NOTESSPOS...
22510707dypit
 
Scala - core features
Łukasz Wójcik
 
Short intro to scala and the play framework
Felipe
 
Macros and reflection in scala 2.10
Johan Andrén
 
1614745770521_vivek macros.pptx
VivekSaini87
 
The Spark Big Data Analytics Platform
Amir Payberah
 
Ad

More from Adam Warski (8)

PDF
What have the annotations done to us?
Adam Warski
 
PPT
Hejdyk maleńka część mazur
Adam Warski
 
PDF
Slick eventsourcing
Adam Warski
 
PDF
Evaluating persistent, replicated message queues
Adam Warski
 
PDF
The no-framework Scala Dependency Injection Framework
Adam Warski
 
PDF
The ideal module system and the harsh reality
Adam Warski
 
PDF
Recommendation systems with Mahout: introduction
Adam Warski
 
PDF
CDI Portable Extensions
Adam Warski
 
What have the annotations done to us?
Adam Warski
 
Hejdyk maleńka część mazur
Adam Warski
 
Slick eventsourcing
Adam Warski
 
Evaluating persistent, replicated message queues
Adam Warski
 
The no-framework Scala Dependency Injection Framework
Adam Warski
 
The ideal module system and the harsh reality
Adam Warski
 
Recommendation systems with Mahout: introduction
Adam Warski
 
CDI Portable Extensions
Adam Warski
 
Ad

Recently uploaded (20)

PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Python basic programing language for automation
DanialHabibi2
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 

Scala Macros