SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Building DSLs with
Scala
Mohit Jaggi
Code Ninja and Big (Data) Troublemaker
Ayasdi
Who am I?
• Software engineer and architect
• Past life: built networking, security and
application delivery appliances using ASICs,
microcode, C, some C++. Operating system
optional.
• This life: distributed systems, (big) data analytics,
machine learning using Java and Scala. And real
servers with a proper operating system!
Why I love Scala?
• Less red tape
• Multi-paradigm
• Exploits the Java ecosystem
• Static typing and type inference
• Same language for everybody from casual script
writer to application programmer to library
designer
Who will find this useful?
• Beginner to intermediate scala programmers
• If you write code, you have APIs
• Library designers
Agenda
• Motivation for DSLs
• Scala Constructs useful for DSLs
• Lessons from my limited experience
Motivation for DSLs
• API Design Considerations
• DSL
• Types of DSLs and tradeoffs
Considerations for a good
API
• sufficient for current needs
• extensible for anticipated needs
• does not preclude unanticipated needs
• forward/backward compatibility
• easy to use
• little or no documentation required, but
• complete documentation available
DSL
• Domain Specific Language
• helps with ease of use part
• e.g. SQL, R, jooq, bigdf
Types of DSLs
• External or standalone
• Internal or embedded
External DSL
• New language from “scratch”
• Write a parser using
something like lex/yacc, antlr
• Write an interpreter or
• Write a code generator
• Manage a run-time
environment(Java?, native?,
REPL?)
Internal DSL
• “internal” or “embedded”
in a general purpose
programming language
• Designed to “feel like” a
different language more
intuitive to the domain
• e.g. Jooq in Java/Scala
feels like SQL
Tradeoffs
• Less work
• More completeness
• Less syntax flexibility
• “global optimizations” hard
• Error messages less
meaningful
• More freedom in syntax
• More “global optimizations”
possible
• Possible to have better error
messages
• More work
• Typically slower without
good code generation
I
n
t
e
r
n
a
l
E
x
t
e
r
n
a
l
Benefit Cost
Why Scala for DSLs?
select(BOOK.ID) from BOOK where BOOK.TITLE === “Scala scala”
select(BOOK.ID).from(BOOK).where(BOOK.TITLE.equal(“Java java”))
Scala Constructs
Useful For DSLs
Vanishing Method Call
• apply() and update() can be called without
naming them
df(“age”) == df.apply(“age”) == df.column(“age”)
df(“age”) = df(“age”) + 1
df.update(df(“age”), df(“age”) + 1)
Simulated dynamic typing
• extend the Dynamic trait
• hides compile errors, is it worth paying that cost?
df.age == df(“age”) == df.selectDynamic(“age”)
def selectDynamic(colName: String) = {

val col = self.column(colName)

if (col == null) logger.error(s"$colName does not match any DF API or column
name")

col

}

def updateDynamic(colName: String)(that: Column): Unit = update(colName, that)
df.age = df.age + 1
df.updateDynamic(“age”)(age + 1)
Dial 0 for operator
• dot is optional, so methods looks like operators
• any symbol can be used as operator
• for example to list people that can buy beer you
can use
df.where(df(“age”).gt(21))
df where (df(“age”) > 21)
• operator ending in colon applies to right
operand, this provides more freedom (~active vs
passive voice)
object orange {
def eat_:(who: String):Unit =
println(s"$who is eating orange”)
}
“monkey” eat_: orange
• careful with operators like ==, use === instead
Free companion object
• hide “new” to make an object
val df = DF.fromCSVFile(…)
• also a good place to put implicit conversions in
Reading between the lines
• implicit conversion to “enrich” types
• can also use “implicit class”
• newer construct “Value Classes” can sometimes replace this
2 MB == ByteSize(2*1024*1024)
class BytesMaker(n: Int) {
def MB = new Bytes(n * 1024 * 1024)
def GB = new Bytes(n * 1024 * 1024 * 1024)
}
case class Bytes(val n: Int) { def print = println(s”bytes=$n") }
object Bytes {
import scala.language.implicitConversions
implicit def intToBytesMaker(n: Int) = new BytesMaker(n)
}
My name is Bond
• Pass by name parameters are useful to pass in
“blocks of code”
def doTwice(action: => Unit) {
action
action
}
doTwice { println("hey") }
Multiple Parameter Lists
• Help avoid unwanted commas and more intuitive
parentheses/braces
def when(predicate: => Boolean)(action: => Unit) = {
if(predicate) action
}
when(1 == 1) { println(“1”) }
instead of
when(1 == 1, println(“1”))
FWIW - API
• Don't provide unnecessary options, if needed
you can always add more; like "salt in a dish",
you can't remove it
• Names meaningful to user not the coder
• Consistent coding style
• Option[T] if truly optional, else exception
FWIW - DSL
• Don’t take it to extremes (like “Baysick”)
• Assume users know some(or lot of) Scala
• Try to generate useful error messages
• Careful with ==, right associative operators, implicit
search order
• Aim to provide gentle slope to Scala instead of none;
basic Scala is simple, your API users will appreciate it
Thanks!
We are hiring
http://engineering.ayasdi.com
http://www.ayasdi.com/careers

Contenu connexe

Tendances

Spark Summit EU talk by Miklos Christine paddling up the stream
Spark Summit EU talk by Miklos Christine paddling up the streamSpark Summit EU talk by Miklos Christine paddling up the stream
Spark Summit EU talk by Miklos Christine paddling up the stream
Spark Summit
 
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
Spark Summit
 
Using SparkR to Scale Data Science Applications in Production. Lessons from t...
Using SparkR to Scale Data Science Applications in Production. Lessons from t...Using SparkR to Scale Data Science Applications in Production. Lessons from t...
Using SparkR to Scale Data Science Applications in Production. Lessons from t...
Spark Summit
 

Tendances (20)

Distributed ML with Dask and Kubernetes
Distributed ML with Dask and KubernetesDistributed ML with Dask and Kubernetes
Distributed ML with Dask and Kubernetes
 
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
Extreme Apache Spark: how in 3 months we created a pipeline that can process ...
 
Real Time Data Processing With Spark Streaming, Node.js and Redis with Visual...
Real Time Data Processing With Spark Streaming, Node.js and Redis with Visual...Real Time Data Processing With Spark Streaming, Node.js and Redis with Visual...
Real Time Data Processing With Spark Streaming, Node.js and Redis with Visual...
 
HBase at Mendeley
HBase at MendeleyHBase at Mendeley
HBase at Mendeley
 
Building a Virtual Data Lake with Apache Arrow
Building a Virtual Data Lake with Apache ArrowBuilding a Virtual Data Lake with Apache Arrow
Building a Virtual Data Lake with Apache Arrow
 
Spark Streaming and MLlib - Hyderabad Spark Group
Spark Streaming and MLlib - Hyderabad Spark GroupSpark Streaming and MLlib - Hyderabad Spark Group
Spark Streaming and MLlib - Hyderabad Spark Group
 
Spark Summit EU talk by Miklos Christine paddling up the stream
Spark Summit EU talk by Miklos Christine paddling up the streamSpark Summit EU talk by Miklos Christine paddling up the stream
Spark Summit EU talk by Miklos Christine paddling up the stream
 
Spark: Interactive To Production
Spark: Interactive To ProductionSpark: Interactive To Production
Spark: Interactive To Production
 
Spark's Role in the Big Data Ecosystem (Spark Summit 2014)
Spark's Role in the Big Data Ecosystem (Spark Summit 2014)Spark's Role in the Big Data Ecosystem (Spark Summit 2014)
Spark's Role in the Big Data Ecosystem (Spark Summit 2014)
 
Koalas: Pandas on Apache Spark
Koalas: Pandas on Apache SparkKoalas: Pandas on Apache Spark
Koalas: Pandas on Apache Spark
 
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
Teaching Apache Spark Clusters to Manage Their Workers Elastically: Spark Sum...
 
Using SparkML to Power a DSaaS (Data Science as a Service) with Kiran Muglurm...
Using SparkML to Power a DSaaS (Data Science as a Service) with Kiran Muglurm...Using SparkML to Power a DSaaS (Data Science as a Service) with Kiran Muglurm...
Using SparkML to Power a DSaaS (Data Science as a Service) with Kiran Muglurm...
 
Apache Arrow: Leveling Up the Data Science Stack
Apache Arrow: Leveling Up the Data Science StackApache Arrow: Leveling Up the Data Science Stack
Apache Arrow: Leveling Up the Data Science Stack
 
Using SparkR to Scale Data Science Applications in Production. Lessons from t...
Using SparkR to Scale Data Science Applications in Production. Lessons from t...Using SparkR to Scale Data Science Applications in Production. Lessons from t...
Using SparkR to Scale Data Science Applications in Production. Lessons from t...
 
Dynamic DDL: Adding Structure to Streaming Data on the Fly with David Winters...
Dynamic DDL: Adding Structure to Streaming Data on the Fly with David Winters...Dynamic DDL: Adding Structure to Streaming Data on the Fly with David Winters...
Dynamic DDL: Adding Structure to Streaming Data on the Fly with David Winters...
 
Lessons from Running Large Scale Spark Workloads
Lessons from Running Large Scale Spark WorkloadsLessons from Running Large Scale Spark Workloads
Lessons from Running Large Scale Spark Workloads
 
Why Functional Programming Is Important in Big Data Era
Why Functional Programming Is Important in Big Data EraWhy Functional Programming Is Important in Big Data Era
Why Functional Programming Is Important in Big Data Era
 
Deep Learning to Production with MLflow & RedisAI
Deep Learning to Production with MLflow & RedisAIDeep Learning to Production with MLflow & RedisAI
Deep Learning to Production with MLflow & RedisAI
 
Apache Arrow: In Theory, In Practice
Apache Arrow: In Theory, In PracticeApache Arrow: In Theory, In Practice
Apache Arrow: In Theory, In Practice
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby Usage
 

Similaire à Building DSLs with Scala

AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
Dmitry Buzdin
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
Avi Kedar
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»
e-Legion
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
Luka Zakrajšek
 

Similaire à Building DSLs with Scala (20)

Spring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_dataSpring one2gx2010 spring-nonrelational_data
Spring one2gx2010 spring-nonrelational_data
 
AestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in ScalaAestasIT - Internal DSLs in Scala
AestasIT - Internal DSLs in Scala
 
Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHP
 
Web Development using Ruby on Rails
Web Development using Ruby on RailsWeb Development using Ruby on Rails
Web Development using Ruby on Rails
 
Spark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin OderskySpark - The Ultimate Scala Collections by Martin Odersky
Spark - The Ultimate Scala Collections by Martin Odersky
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGNIntroducing Scala to your Ruby/Java Shop : My experiences at IGN
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
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
 
No sql Database
No sql DatabaseNo sql Database
No sql Database
 
Why ruby and rails
Why ruby and railsWhy ruby and rails
Why ruby and rails
 
Scala and Spring
Scala and SpringScala and Spring
Scala and Spring
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
MySQL And Search At Craigslist
MySQL And Search At CraigslistMySQL And Search At Craigslist
MySQL And Search At Craigslist
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Software Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and PracticesSoftware Architecture: Principles, Patterns and Practices
Software Architecture: Principles, Patterns and Practices
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»
 
Scala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big DataScala and Spark are Ideal for Big Data
Scala and Spark are Ideal for Big Data
 
Typesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and PlayTypesafe stack - Scala, Akka and Play
Typesafe stack - Scala, Akka and Play
 

Dernier

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Building DSLs with Scala

  • 1. Building DSLs with Scala Mohit Jaggi Code Ninja and Big (Data) Troublemaker Ayasdi
  • 2. Who am I? • Software engineer and architect • Past life: built networking, security and application delivery appliances using ASICs, microcode, C, some C++. Operating system optional. • This life: distributed systems, (big) data analytics, machine learning using Java and Scala. And real servers with a proper operating system!
  • 3. Why I love Scala? • Less red tape • Multi-paradigm • Exploits the Java ecosystem • Static typing and type inference • Same language for everybody from casual script writer to application programmer to library designer
  • 4. Who will find this useful? • Beginner to intermediate scala programmers • If you write code, you have APIs • Library designers
  • 5. Agenda • Motivation for DSLs • Scala Constructs useful for DSLs • Lessons from my limited experience
  • 6. Motivation for DSLs • API Design Considerations • DSL • Types of DSLs and tradeoffs
  • 7. Considerations for a good API • sufficient for current needs • extensible for anticipated needs • does not preclude unanticipated needs • forward/backward compatibility • easy to use • little or no documentation required, but • complete documentation available
  • 8. DSL • Domain Specific Language • helps with ease of use part • e.g. SQL, R, jooq, bigdf
  • 9. Types of DSLs • External or standalone • Internal or embedded
  • 10. External DSL • New language from “scratch” • Write a parser using something like lex/yacc, antlr • Write an interpreter or • Write a code generator • Manage a run-time environment(Java?, native?, REPL?)
  • 11. Internal DSL • “internal” or “embedded” in a general purpose programming language • Designed to “feel like” a different language more intuitive to the domain • e.g. Jooq in Java/Scala feels like SQL
  • 12. Tradeoffs • Less work • More completeness • Less syntax flexibility • “global optimizations” hard • Error messages less meaningful • More freedom in syntax • More “global optimizations” possible • Possible to have better error messages • More work • Typically slower without good code generation I n t e r n a l E x t e r n a l Benefit Cost
  • 13. Why Scala for DSLs? select(BOOK.ID) from BOOK where BOOK.TITLE === “Scala scala” select(BOOK.ID).from(BOOK).where(BOOK.TITLE.equal(“Java java”))
  • 15. Vanishing Method Call • apply() and update() can be called without naming them df(“age”) == df.apply(“age”) == df.column(“age”) df(“age”) = df(“age”) + 1 df.update(df(“age”), df(“age”) + 1)
  • 16. Simulated dynamic typing • extend the Dynamic trait • hides compile errors, is it worth paying that cost? df.age == df(“age”) == df.selectDynamic(“age”) def selectDynamic(colName: String) = {
 val col = self.column(colName)
 if (col == null) logger.error(s"$colName does not match any DF API or column name")
 col
 }
 def updateDynamic(colName: String)(that: Column): Unit = update(colName, that) df.age = df.age + 1 df.updateDynamic(“age”)(age + 1)
  • 17. Dial 0 for operator • dot is optional, so methods looks like operators • any symbol can be used as operator • for example to list people that can buy beer you can use df.where(df(“age”).gt(21)) df where (df(“age”) > 21)
  • 18. • operator ending in colon applies to right operand, this provides more freedom (~active vs passive voice) object orange { def eat_:(who: String):Unit = println(s"$who is eating orange”) } “monkey” eat_: orange • careful with operators like ==, use === instead
  • 19. Free companion object • hide “new” to make an object val df = DF.fromCSVFile(…) • also a good place to put implicit conversions in
  • 20. Reading between the lines • implicit conversion to “enrich” types • can also use “implicit class” • newer construct “Value Classes” can sometimes replace this 2 MB == ByteSize(2*1024*1024) class BytesMaker(n: Int) { def MB = new Bytes(n * 1024 * 1024) def GB = new Bytes(n * 1024 * 1024 * 1024) } case class Bytes(val n: Int) { def print = println(s”bytes=$n") } object Bytes { import scala.language.implicitConversions implicit def intToBytesMaker(n: Int) = new BytesMaker(n) }
  • 21. My name is Bond • Pass by name parameters are useful to pass in “blocks of code” def doTwice(action: => Unit) { action action } doTwice { println("hey") }
  • 22. Multiple Parameter Lists • Help avoid unwanted commas and more intuitive parentheses/braces def when(predicate: => Boolean)(action: => Unit) = { if(predicate) action } when(1 == 1) { println(“1”) } instead of when(1 == 1, println(“1”))
  • 23. FWIW - API • Don't provide unnecessary options, if needed you can always add more; like "salt in a dish", you can't remove it • Names meaningful to user not the coder • Consistent coding style • Option[T] if truly optional, else exception
  • 24. FWIW - DSL • Don’t take it to extremes (like “Baysick”) • Assume users know some(or lot of) Scala • Try to generate useful error messages • Careful with ==, right associative operators, implicit search order • Aim to provide gentle slope to Scala instead of none; basic Scala is simple, your API users will appreciate it