SlideShare a Scribd company logo
Internal DSLs in Scala
Andrey Adamovich
Aestas/IT
What’s in this
presentation?
 Definition and usage of DSLs
 Overview of Scala features that
  can be used to create internal
  DSL
 Examples of Scala-based DSLs
 Some links and reading
  material
 Questions
WORLD OF DSLS
What is DSL?
Domain-Specific Language

”   A Domain-Specific Language is a programming
    language or executable specification language that
    offers, through appropriate notations and
    abstractions, expressive power focused on, and
    usually restricted to, a particular problem
    domain.

”   The opposite is:
    • a general-purpose programming language, such
      as C, Java or Python,
    • or a general-purpose modeling language such as
      the Unified Modeling Language (UML).
Examples of DSL

”   
    
    
        Examples of domain-specific languages include:
        HTML,
        Logo for children,
       Verilog    and    VHDL  hardware      description
        languages,
       Mata for matrix programming,
       Mathematica     and    Maxima    for    symbolic
        mathematics,
       spreadsheet formulas and macros,
       SQL for relational database queries,
       YACC grammars for creating parsers,
       regular expressions for specifying lexers,
       the Generic Eclipse Modeling System for creating
        diagramming languages,
       Csound for sound and music synthesis,
       and the input languages of GraphViz and GrGen,
        software packages used for graph layout and
        graph rewriting.
Goals of DSL
”      Use a more expressive language than a
        general-purpose one
       Share a common metaphor of
        understanding between developers and
        subject matter experts
       Have domain experts help with the design of
        the business logic of an application
       Avoid cluttering business code with too
        much boilerplate technical code thanks to
        a clean separation
       Let business rules have their own lifecycle
                               Guillaume Laforge
                               Groovy Project Manager
What is internal DSL?

”   Internal DSLs are particular
    ways of using a host language
    to give the host language the
    feel of a particular language
                       Martin Fowler
Library vs. DSL
   Is there any difference between
    a well-structured library or
    API and an internal DSL?
   Not much, except for the
    following:
    • Internal DSL does not look like
      code in host language
    • It’s more readable in general and
      is much closer to natural language
Fluent API

”   In software engineering, a fluent
    interface (as first coined by Eric Evans
    and Martin Fowler) is an
    implementation of an object oriented
    API that aims to provide for more
    readable code.

”   A fluent interface is normally
    implemented by using method
    chaining to relay the instruction
    context of a subsequent call (but a
    fluent interface entails more than
    just method chaining).
Fluent API examples
Mockito       http://code.google.com/p/mockito/




Guava     http://code.google.com/p/guava-libraries/
SCALA
Features of Scala
 Lightweight syntax
 Combines functional and object-
  oriented aproaches
 Advanced type system:
  everything has a type
 Strong type inference
 Performance comparable to
  Java
 Fully interoperable with Java
What makes internal DSL
possible in Scala?
 ”Dot-free”, infix and postfix
  operator notation
 ”Bracket-free” function calls
 (Almost) any character can be
  used in method names
 Implicit conversions
 Advanced type system
 By-name parameters and
  currying
Lightweight syntax

val numbers = List(1, 2, 3)

numbers map { x => x + 1 }

numbers sortWith { (x, y) => x > y }

numbers map { _ + 1 } sortWith { _ > _ }

numbers size
Implicit conversions
Map( "first" -> "Test", "second" -> "Code" )




/* Defines a new method 'sort' for array objects */
object implicits extends Application {
  implicit def arrayWrapper[A : ClassManifest](x: Array[A]) =
    new {
      def sort(p: (A, A) => Boolean) = {
        util.Sorting.stableSort(x, p); x
      }
    }
  val x = Array(2, 3, 1, 4)
  println("x = "+ x.sort((x: Int, y: Int) => x < y))
}
By-name parameters

debug("This" + " is" + " very" + " costly!")

def debug(msg: => String): Unit =
  if (isDebugEnabled()) println(msg)




spawn(println("I run in different thread!"))

def spawn(p: => Unit) = {
    val t = new Thread() { override def run() = p }
    t.start()
  }
Curryng I

”   In mathematics and computer
    science, currying is the technique
    of transforming a function that
    takes multiple arguments (or an
    n-tuple of arguments) in such a
    way that it can be called as a
    chain of functions each with a
    single argument (partial
    application).
Curryng II
using(new BufferedReader(new FileReader("file"))) { r =>
  var count = 0
  while (r.readLine != null) count += 1
  println(count)
}

def using[T <: { def close() }]
    (resource: T)
    (block: T => Unit)
{
  try {
    block(resource)
  } finally {
    if (resource != null) resource.close()
  }
}
Advanced type system
DSL EXAMPLES
Baysick
ScalaBasicRunner.scala:


object    ScalaBasicRunner extends Baysick with Application {
    10    PRINT "Scala"
    20    LET ('number := 1)
    30    IF 'number > 0 THEN 50
    40    PRINT "Java"
    50    PRINT "rulez!"
    60    END

     RUN
}
Time DSL
import org.scala_tools.time.Imports._

DateTime.now

DateTime.now.hour(2).minute(45).second(10)

DateTime.now + 2.months

DateTime.nextMonth < DateTime.now + 2.months

DateTime.now to DateTime.tomorrow

(DateTime.now to DateTime.nextSecond).millis

2.hours + 45.minutes + 10.seconds

(2.hours + 45.minutes + 10.seconds).millis

2.months + 3.days
Spring Integration DSL

val messageFlow =
     filter using
        { payload: String => payload == "World" } -->
     transform using
        { payload: String => "Hello " + payload } -->
     handle using
        { payload: String => println(payload) }

messageFlow.send("World")
READING MATERIAL
Books
Programming in Scala, Second Edition
 Martin Odersky, Lex Spoon, and Bill
                            Venners




                     DSLs in Action
                     Debasish Ghosh
Links
   http://www.scala-lang.org/

   https://github.com/jorgeortiz85/scala-
    time

   http://blog.springsource.org/2012/03/05/i
    ntroducing-spring-integration-scala-dsl/

   http://blog.fogus.me/2009/03/26/baysick-
    a-scala-dsl-implementing-basic/

   http://habrahabr.ru/post/98288/
QUESTIONS

More Related Content

What's hot (17)

PDF
Preparing for Scala 3
Martin Odersky
 
PPT
Devoxx
Martin Odersky
 
PPTX
Introduction to Scala
Mohammad Hossein Rimaz
 
PPTX
Namespace in C++ Programming Language
Himanshu Choudhary
 
PPTX
flatMap Oslo presentation slides
Martin Odersky
 
PPTX
The Evolution of Scala
Martin Odersky
 
PPTX
Concurrency Constructs Overview
stasimus
 
PPTX
Neo4 + Grails
stasimus
 
PDF
What To Leave Implicit
Martin Odersky
 
PDF
Simplicitly
Martin Odersky
 
PPTX
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
PDF
Introduction to Scala
Saleem Ansari
 
PPTX
Introduction to Scala
Rahul Jain
 
PPT
73d32 session1 c++
Mukund Trivedi
 
PPT
ICON UK '13 - Apache Software: The FREE Java toolbox you didn't know you had !!
panagenda
 
PPTX
A Brief Intro to Scala
Tim Underwood
 
PPTX
What To Leave Implicit
Martin Odersky
 
Preparing for Scala 3
Martin Odersky
 
Introduction to Scala
Mohammad Hossein Rimaz
 
Namespace in C++ Programming Language
Himanshu Choudhary
 
flatMap Oslo presentation slides
Martin Odersky
 
The Evolution of Scala
Martin Odersky
 
Concurrency Constructs Overview
stasimus
 
Neo4 + Grails
stasimus
 
What To Leave Implicit
Martin Odersky
 
Simplicitly
Martin Odersky
 
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
Introduction to Scala
Saleem Ansari
 
Introduction to Scala
Rahul Jain
 
73d32 session1 c++
Mukund Trivedi
 
ICON UK '13 - Apache Software: The FREE Java toolbox you didn't know you had !!
panagenda
 
A Brief Intro to Scala
Tim Underwood
 
What To Leave Implicit
Martin Odersky
 

Similar to AestasIT - Internal DSLs in Scala (20)

PDF
Building DSLs: Marriage of High Essence and Groovy Metaprogramming
Skills Matter
 
PDF
Domain Specific Languages
elliando dias
 
PDF
DSLs: what, why, how
Mikhail Barash
 
PDF
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
 
PDF
Metamorphic Domain-Specific Languages
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PDF
Api and Fluency
Stefano Fago
 
PDF
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
Harshal Hayatnagarkar
 
PDF
GGUG:Practical DSL Design
Skills Matter
 
PDF
Writing a DSL for the Dense with Scala - JVMCon
Jan-Hendrik Kuperus
 
PDF
groovy DSLs from beginner to expert
Paul King
 
PDF
Oopsla 2008 Panel Ds Ls The Good The Bad And The Ugly
OOPSLA2008
 
PDF
Os Alrubaie Ruby
oscon2007
 
PPTX
BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...
SQALab
 
PPTX
Bdd and dsl как способ построения коммуникации на проекте
ISsoft
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PPTX
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
PDF
Principles Of Programing Languages
Matthew McCullough
 
Building DSLs: Marriage of High Essence and Groovy Metaprogramming
Skills Matter
 
Domain Specific Languages
elliando dias
 
DSLs: what, why, how
Mikhail Barash
 
Building DSLs On CLR and DLR (Microsoft.NET)
Vitaly Baum
 
Metamorphic Domain-Specific Languages
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
Api and Fluency
Stefano Fago
 
DSL Construction with Ruby - ThoughtWorks Masterclass Series 2009
Harshal Hayatnagarkar
 
GGUG:Practical DSL Design
Skills Matter
 
Writing a DSL for the Dense with Scala - JVMCon
Jan-Hendrik Kuperus
 
groovy DSLs from beginner to expert
Paul King
 
Oopsla 2008 Panel Ds Ls The Good The Bad And The Ugly
OOPSLA2008
 
Os Alrubaie Ruby
oscon2007
 
BDD or DSL как способ построения коммуникации на проекте - опыт комплексного ...
SQALab
 
Bdd and dsl как способ построения коммуникации на проекте
ISsoft
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Real world DSL - making technical and business people speaking the same language
Mario Fusco
 
Principles Of Programing Languages
Matthew McCullough
 
Ad

More from Dmitry Buzdin (20)

PDF
How Payment Cards Really Work?
Dmitry Buzdin
 
PDF
Как построить свой фреймворк для автотестов?
Dmitry Buzdin
 
PDF
How to grow your own Microservice?
Dmitry Buzdin
 
PDF
How to Build Your Own Test Automation Framework?
Dmitry Buzdin
 
PDF
Delivery Pipeline for Windows Machines
Dmitry Buzdin
 
PPTX
Big Data Processing Using Hadoop Infrastructure
Dmitry Buzdin
 
PDF
JOOQ and Flyway
Dmitry Buzdin
 
PDF
Developing Useful APIs
Dmitry Buzdin
 
PPTX
Whats New in Java 8
Dmitry Buzdin
 
PPTX
Архитектура Ленты на Одноклассниках
Dmitry Buzdin
 
PDF
Dart Workshop
Dmitry Buzdin
 
PDF
Riding Redis @ask.fm
Dmitry Buzdin
 
PDF
Rubylight JUG Contest Results Part II
Dmitry Buzdin
 
PDF
Rubylight Pattern-Matching Solutions
Dmitry Buzdin
 
PDF
Refactoring to Macros with Clojure
Dmitry Buzdin
 
PPTX
Poor Man's Functional Programming
Dmitry Buzdin
 
PDF
Rubylight programming contest
Dmitry Buzdin
 
PPTX
Continuous Delivery
Dmitry Buzdin
 
PPTX
Introduction to DevOps
Dmitry Buzdin
 
PDF
Thread Dump Analysis
Dmitry Buzdin
 
How Payment Cards Really Work?
Dmitry Buzdin
 
Как построить свой фреймворк для автотестов?
Dmitry Buzdin
 
How to grow your own Microservice?
Dmitry Buzdin
 
How to Build Your Own Test Automation Framework?
Dmitry Buzdin
 
Delivery Pipeline for Windows Machines
Dmitry Buzdin
 
Big Data Processing Using Hadoop Infrastructure
Dmitry Buzdin
 
JOOQ and Flyway
Dmitry Buzdin
 
Developing Useful APIs
Dmitry Buzdin
 
Whats New in Java 8
Dmitry Buzdin
 
Архитектура Ленты на Одноклассниках
Dmitry Buzdin
 
Dart Workshop
Dmitry Buzdin
 
Riding Redis @ask.fm
Dmitry Buzdin
 
Rubylight JUG Contest Results Part II
Dmitry Buzdin
 
Rubylight Pattern-Matching Solutions
Dmitry Buzdin
 
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Poor Man's Functional Programming
Dmitry Buzdin
 
Rubylight programming contest
Dmitry Buzdin
 
Continuous Delivery
Dmitry Buzdin
 
Introduction to DevOps
Dmitry Buzdin
 
Thread Dump Analysis
Dmitry Buzdin
 
Ad

Recently uploaded (20)

PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
TrustArc Webinar - Data Privacy Trends 2025: Mid-Year Insights & Program Stra...
TrustArc
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Persuasive AI: risks and opportunities in the age of digital debate
Speck&Tech
 

AestasIT - Internal DSLs in Scala

  • 1. Internal DSLs in Scala Andrey Adamovich Aestas/IT
  • 2. What’s in this presentation?  Definition and usage of DSLs  Overview of Scala features that can be used to create internal DSL  Examples of Scala-based DSLs  Some links and reading material  Questions
  • 4. What is DSL? Domain-Specific Language ” A Domain-Specific Language is a programming language or executable specification language that offers, through appropriate notations and abstractions, expressive power focused on, and usually restricted to, a particular problem domain. ” The opposite is: • a general-purpose programming language, such as C, Java or Python, • or a general-purpose modeling language such as the Unified Modeling Language (UML).
  • 5. Examples of DSL ”    Examples of domain-specific languages include: HTML, Logo for children,  Verilog and VHDL hardware description languages,  Mata for matrix programming,  Mathematica and Maxima for symbolic mathematics,  spreadsheet formulas and macros,  SQL for relational database queries,  YACC grammars for creating parsers,  regular expressions for specifying lexers,  the Generic Eclipse Modeling System for creating diagramming languages,  Csound for sound and music synthesis,  and the input languages of GraphViz and GrGen, software packages used for graph layout and graph rewriting.
  • 6. Goals of DSL ”  Use a more expressive language than a general-purpose one  Share a common metaphor of understanding between developers and subject matter experts  Have domain experts help with the design of the business logic of an application  Avoid cluttering business code with too much boilerplate technical code thanks to a clean separation  Let business rules have their own lifecycle Guillaume Laforge Groovy Project Manager
  • 7. What is internal DSL? ” Internal DSLs are particular ways of using a host language to give the host language the feel of a particular language Martin Fowler
  • 8. Library vs. DSL  Is there any difference between a well-structured library or API and an internal DSL?  Not much, except for the following: • Internal DSL does not look like code in host language • It’s more readable in general and is much closer to natural language
  • 9. Fluent API ” In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code. ” A fluent interface is normally implemented by using method chaining to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining).
  • 10. Fluent API examples Mockito http://code.google.com/p/mockito/ Guava http://code.google.com/p/guava-libraries/
  • 11. SCALA
  • 12. Features of Scala  Lightweight syntax  Combines functional and object- oriented aproaches  Advanced type system: everything has a type  Strong type inference  Performance comparable to Java  Fully interoperable with Java
  • 13. What makes internal DSL possible in Scala?  ”Dot-free”, infix and postfix operator notation  ”Bracket-free” function calls  (Almost) any character can be used in method names  Implicit conversions  Advanced type system  By-name parameters and currying
  • 14. Lightweight syntax val numbers = List(1, 2, 3) numbers map { x => x + 1 } numbers sortWith { (x, y) => x > y } numbers map { _ + 1 } sortWith { _ > _ } numbers size
  • 15. Implicit conversions Map( "first" -> "Test", "second" -> "Code" ) /* Defines a new method 'sort' for array objects */ object implicits extends Application { implicit def arrayWrapper[A : ClassManifest](x: Array[A]) = new { def sort(p: (A, A) => Boolean) = { util.Sorting.stableSort(x, p); x } } val x = Array(2, 3, 1, 4) println("x = "+ x.sort((x: Int, y: Int) => x < y)) }
  • 16. By-name parameters debug("This" + " is" + " very" + " costly!") def debug(msg: => String): Unit = if (isDebugEnabled()) println(msg) spawn(println("I run in different thread!")) def spawn(p: => Unit) = { val t = new Thread() { override def run() = p } t.start() }
  • 17. Curryng I ” In mathematics and computer science, currying is the technique of transforming a function that takes multiple arguments (or an n-tuple of arguments) in such a way that it can be called as a chain of functions each with a single argument (partial application).
  • 18. Curryng II using(new BufferedReader(new FileReader("file"))) { r => var count = 0 while (r.readLine != null) count += 1 println(count) } def using[T <: { def close() }] (resource: T) (block: T => Unit) { try { block(resource) } finally { if (resource != null) resource.close() } }
  • 21. Baysick ScalaBasicRunner.scala: object ScalaBasicRunner extends Baysick with Application { 10 PRINT "Scala" 20 LET ('number := 1) 30 IF 'number > 0 THEN 50 40 PRINT "Java" 50 PRINT "rulez!" 60 END RUN }
  • 22. Time DSL import org.scala_tools.time.Imports._ DateTime.now DateTime.now.hour(2).minute(45).second(10) DateTime.now + 2.months DateTime.nextMonth < DateTime.now + 2.months DateTime.now to DateTime.tomorrow (DateTime.now to DateTime.nextSecond).millis 2.hours + 45.minutes + 10.seconds (2.hours + 45.minutes + 10.seconds).millis 2.months + 3.days
  • 23. Spring Integration DSL val messageFlow = filter using { payload: String => payload == "World" } --> transform using { payload: String => "Hello " + payload } --> handle using { payload: String => println(payload) } messageFlow.send("World")
  • 25. Books Programming in Scala, Second Edition Martin Odersky, Lex Spoon, and Bill Venners DSLs in Action Debasish Ghosh
  • 26. Links  http://www.scala-lang.org/  https://github.com/jorgeortiz85/scala- time  http://blog.springsource.org/2012/03/05/i ntroducing-spring-integration-scala-dsl/  http://blog.fogus.me/2009/03/26/baysick- a-scala-dsl-implementing-basic/  http://habrahabr.ru/post/98288/