SlideShare a Scribd company logo
Introduction to
QUASIQUOTES
By :-
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
By :-
SAHIL SAWHNEY
Software Consultant
KNOLDUS SOFTWARE LLP
Agenda
● Interpolators, a recap.
● What are quasiqoute?
● Required dependencies and imports.
● ShowRaw and showCode
● Lifting, Unlifting
● Compiling and executing ASTs
● Use case
● References
Revisiting Interpolators
➔ It is a mechanism that enable us to
sew/embed/bind WORDS in between a
processed/unprocessed string literal.
➔ We learned about s, raw and f string
interpolators
➔ Now let us uncover what quotation is which is
based on the fundamental of string
interpolators
What are Quasiquotes?
Quasiquotes are a neat notation that lets you
manipulate Scala syntax trees (AST) with
ease. Quotation syntax is in just another
usage of extensible string interpolation.
How neat are they?
val tree = q"i am { a quasiquote }"
and we have our AST.
What just happened?
The code wrapped inside q”...” is picked up and
an AST is formed from it.
NOTE →
The expression yielded by q”...” is just a tree
which is neither compiled nor executed
Justification
What according to you shall be the output for :
● scalac -Xshow-phases
(no compilation has occurred)
● Q”10 / 0”
(no execution has occurred)
Dependencies and imports.
➔ Dependencies :
"org.scala-lang" % "scala-reflect" % "2.11.8"
➔ Imports :
import scala.reflect.runtime.universe
import universe._
showRaw and showCode
➔ Understanding the pretty printers with example :
showCode : AST ––> equivalent source code
showRaw : AST ––> organization of the tree
Comparing trees
➔ ‘equalsStructure’ is used to determine if two
AST’s are structurally equal or not.
➔ Returns a true if AST are same.
q"I work at knoldus" equalsStructure q”{your
guess}”
Unqouting
➔Whenever we unquote an expression of Tree
type in a quasiquote, it will structurally
substitute that tree into the location.
➔Val a = q"class AAA"
➔Val b = q"class BBB"
➔q”$a + $b”
Splicing
➔Splicing is a way to unquote a variable number
of elements
➔One possible example can be a method call.
Discuss Example 2
Lifting
● Lifting is an extensible way to unquote custom data types
in quasiquotes.
● Int, String, Float (basic types) are all Liftable by default
● Its just
“ T –—> Tree “
val no =5
q”$no + $no”
Lifting cont..
● Liftable type is just a trait with a single abstract method that
defines a mapping of given type to tree
trait Liftable[T] {
def apply(value: T): Tree
}
● Whenever there is an implicit value of Liftable[T] available,
one can unquote T (our custom type) in quasiquotes. This
design pattern is known as a type class.
Lifting Custom Types
Demonstrating an Example of case class (most widely used
way to implement custom types in Scala) :-
case class Student(name: String, age: Int)
object Student {
implicit val lift = Liftable[Student] { stu =>
q"_root_.Student(${stu.name}, ${stu.age})"
}
}
Unlifting
● Unlifting is the reverse operation to lifting.
● It takes a tree and recovers value from it.
● Its just “ Tree –—> Option[T] “ . Why option?
val q"${left: Int} + ${right: Int}" = q"2 + 2"
Unlifting Cont..
● Unliftable type is just a trait with a single abstract method
that defines a mapping of given type to tree.
trait Unliftable[T] {
def unapply(tree: Tree): Option[T]
}
● Due to the fact that tree might not be a representation of
our data type, the return type of unapply is Option[T]
rather than just T
Unlifting Custom Types
Just add following to previous example
implicit val unliftIt = Unliftable[Student] {
case q"Student(${name: String}, ${age: Int})" =>
Student(name, age)
}
Example 3
Compiling and executing the
AST
Toolbox api serves the purpose of compiling the
AST.
Dependencies →
"org.scala-lang" % "scala-compiler" % "2.11.8"
Imports ->
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
Compiling
The AST can be compiled using the compile
method of Toolbox with following signature :
abstract def compile(tree : U.Tree): () Any⇒
It throws an compilation error if compilation fails.
Executing
The AST can be compiled and executed using the
eval method of Toolbox with following signature :
abstract def eval(tree : U.Tree): Any
It throws an compilation error if compilation fails
and runtime error if execution fails.
Use cases
● Easy AST manipulation
● Offline code generation(AST to corrosponding
code using showCode method)
● Just in time compilation using Toolbox api
References
http://www.scala-lang.org/api/2.12.0-M4/scala-compiler
http://docs.scala-lang.org/overviews/quasiquotes/intro
https://www.youtube.com/watch?v=_c6SMsZNxms
http://www.scala-lang.org/api/2.12.0-M4/scala-compiler
http://docs.scala-lang.org/overviews/quasiquotes/intro
https://www.youtube.com/watch?v=_c6SMsZNxms
Thank You !!!

More Related Content

PPTX
.NET F# Class constructor
PPTX
Vardump and printr in php
PDF
Introducing Pattern Matching in Scala
PDF
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
ODP
Knolx Session: Introducing Extractors in Scala
PPTX
Relational operation final
PDF
Javascript foundations: Introducing OO
ODP
Knolx Session : Built-In Control Structures in Scala
.NET F# Class constructor
Vardump and printr in php
Introducing Pattern Matching in Scala
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
Knolx Session: Introducing Extractors in Scala
Relational operation final
Javascript foundations: Introducing OO
Knolx Session : Built-In Control Structures in Scala

Viewers also liked (20)

ODP
Event sourcing with Eventuate
ODP
Walk-through: Amazon ECS
ODP
Introduction to Structured Streaming
ODP
BDD with Cucumber
ODP
Introduction to BDD
ODP
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
ODP
HTML5, CSS, JavaScript Style guide and coding conventions
ODP
Deep dive into sass
ODP
Akka Finite State Machine
PPTX
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
ODP
Introduction to AWS IAM
PDF
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
ODP
Http programming in play
PDF
Oracle Database 12c Essentials 1Z0-497 exam questions
ODP
Drilling the Async Library
ODP
Getting Started With AureliaJs
ODP
Akka streams
ODP
Introduction to Scala JS
ODP
Realm Mobile Database - An Introduction
ODP
String interpolation
Event sourcing with Eventuate
Walk-through: Amazon ECS
Introduction to Structured Streaming
BDD with Cucumber
Introduction to BDD
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
HTML5, CSS, JavaScript Style guide and coding conventions
Deep dive into sass
Akka Finite State Machine
Lessons Learned From PayPal: Implementing Back-Pressure With Akka Streams And...
Introduction to AWS IAM
Building Streaming And Fast Data Applications With Spark, Mesos, Akka, Cassan...
Http programming in play
Oracle Database 12c Essentials 1Z0-497 exam questions
Drilling the Async Library
Getting Started With AureliaJs
Akka streams
Introduction to Scala JS
Realm Mobile Database - An Introduction
String interpolation
Ad

Similar to Introduction to Quasiquotes (20)

PDF
scala.reflect, Eugene Burmako
PDF
Евгений Бурмако «scala.reflect»
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
PPTX
Practical type mining in Scala
PDF
Exploring type level programming in Scala
PDF
Snakes and ladders
PDF
Template Haskell
PPTX
Scala 3 Is Coming: Martin Odersky Shares What To Know
PDF
Types Working for You, Not Against You
PPTX
Speaking Scala: Refactoring for Fun and Profit (Workshop)
PDF
Power of functions in a typed world
PPT
scala.ppt
PDF
What can scala puzzlers teach us
PDF
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
PDF
Scala cheatsheet
PDF
The Great Scala Makeover
PDF
Scala fun part: Reflection(runtime)
PDF
Programming in scala - 1
PPTX
Scala training workshop 02
PPTX
Scala Refactoring for Fun and Profit
scala.reflect, Eugene Burmako
Евгений Бурмако «scala.reflect»
Metaprogramming in Scala 2.10, Eugene Burmako,
Practical type mining in Scala
Exploring type level programming in Scala
Snakes and ladders
Template Haskell
Scala 3 Is Coming: Martin Odersky Shares What To Know
Types Working for You, Not Against You
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Power of functions in a typed world
scala.ppt
What can scala puzzlers teach us
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
Scala cheatsheet
The Great Scala Makeover
Scala fun part: Reflection(runtime)
Programming in scala - 1
Scala training workshop 02
Scala Refactoring for Fun and Profit
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PDF
Nekopoi APK 2025 free lastest update
PPTX
Online Work Permit System for Fast Permit Processing
PDF
medical staffing services at VALiNTRY
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
System and Network Administraation Chapter 3
PPTX
Transform Your Business with a Software ERP System
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPT
Introduction Database Management System for Course Database
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Digital Strategies for Manufacturing Companies
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
L1 - Introduction to python Backend.pptx
Nekopoi APK 2025 free lastest update
Online Work Permit System for Fast Permit Processing
medical staffing services at VALiNTRY
Navsoft: AI-Powered Business Solutions & Custom Software Development
System and Network Administraation Chapter 3
Transform Your Business with a Software ERP System
ISO 45001 Occupational Health and Safety Management System
How to Migrate SBCGlobal Email to Yahoo Easily
Odoo Companies in India – Driving Business Transformation.pdf
2025 Textile ERP Trends: SAP, Odoo & Oracle
Operating system designcfffgfgggggggvggggggggg
ManageIQ - Sprint 268 Review - Slide Deck
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Upgrade and Innovation Strategies for SAP ERP Customers
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Introduction Database Management System for Course Database
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Digital Strategies for Manufacturing Companies
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
L1 - Introduction to python Backend.pptx

Introduction to Quasiquotes