SlideShare une entreprise Scribd logo
1  sur  33
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
Ngoc Dao
 

Tendances (20)

camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
es6
es6es6
es6
 
Model with actors and implement with Akka
Model with actors and implement with AkkaModel with actors and implement with Akka
Model with actors and implement with Akka
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
AS3Commons Introduction
AS3Commons IntroductionAS3Commons Introduction
AS3Commons Introduction
 
TypeScript
TypeScriptTypeScript
TypeScript
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014User defined-functions-cassandra-summit-eu-2014
User defined-functions-cassandra-summit-eu-2014
 
Useful and Practical Functionalities in Realm
Useful and Practical Functionalities in RealmUseful and Practical Functionalities in Realm
Useful and Practical Functionalities in Realm
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
Introduction to Scala : Clueda
Introduction to Scala : CluedaIntroduction to Scala : Clueda
Introduction to Scala : Clueda
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Elm kyivfprog 2015
Elm kyivfprog 2015Elm kyivfprog 2015
Elm kyivfprog 2015
 

Similaire à Scala Macros

Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Scala overview
Scala overviewScala overview
Scala overview
Steve Min
 

Similaire à Scala Macros (20)

Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Project kepler compile time metaprogramming for scala
Project kepler compile time metaprogramming for scalaProject kepler compile time metaprogramming for scala
Project kepler compile time metaprogramming for scala
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala Macros
Scala MacrosScala Macros
Scala Macros
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala for the doubters
Scala for the doubtersScala for the doubters
Scala for the doubters
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Dax Declarative Api For Xml
Dax   Declarative Api For XmlDax   Declarative Api For Xml
Dax Declarative Api For Xml
 
Scala overview
Scala overviewScala overview
Scala overview
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Metaprogramming  in Scala 2.10, Eugene Burmako, Metaprogramming  in Scala 2.10, Eugene Burmako,
Metaprogramming in Scala 2.10, Eugene Burmako,
 
A Tale of Two APIs: Using Spark Streaming In Production
A Tale of Two APIs: Using Spark Streaming In ProductionA Tale of Two APIs: Using Spark Streaming In Production
A Tale of Two APIs: Using Spark Streaming In Production
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Lightning fast analytics with Spark and Cassandra
Lightning fast analytics with Spark and CassandraLightning fast analytics with Spark and Cassandra
Lightning fast analytics with Spark and Cassandra
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 

Plus de Adam Warski

The ideal module system and the harsh reality
The ideal module system and the harsh realityThe ideal module system and the harsh reality
The ideal module system and the harsh reality
Adam Warski
 

Plus de Adam Warski (8)

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

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

Scala Macros