Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline...

120
. . Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra Scala: Growing a Language Steven She SE2: Software Design & Architecture July 15, 2008 . Steven She Scala: Growing a Language 1/43

Transcript of Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline...

Page 1: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

ScalaGrowing a Language

Steven She

SE2 Software Design amp Architecture

July 15 2008

Steven She Scala Growing a Language 143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming language

bull object-orientedhellip

and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip

and functionalbull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip

but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 2: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming language

bull object-orientedhellip

and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip

and functionalbull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip

but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 3: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip

and functionalbull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip

but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 4: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functional

bull like a dynamic languagehellip

but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip

but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 5: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip

but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 6: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typed

bull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 7: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 8: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

What is Scala

Scala ishellip

bull a general purpose programming languagebull object-orientedhellip and functionalbull like a dynamic languagehellip but is really statically typedbull (almost) seemlessly integrated with Java

Steven She Scala Growing a Language 243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 9: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

A Brief History

bull Designed by Martin Odersky Professor at EPFLbull In 1998 created GJ Implemented into Java 5 in 2004bull GJ compiler became javac (v13 onward)bull Design for Scala started in 2001 first release in 2003bull Scala version 2 was released 2006

Steven She Scala Growing a Language 343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 10: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 11: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language

Scala stands for Scalable Language

Cathedralbull One plan one designerbull Long arduous development timebull Few changes made to the planbull Java C C++ etc

Steven She Scala Growing a Language 443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 12: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Growing a Language (cont)

Scala stands for Scalable Language

Bazaarbull No single planbull Users contribute to the design of thesystem

bull Language grows as the users see fitbull Scala was designed to support a bazaar

0httpcatborgesrwritingscathedral-bazaarcathedral-bazaar

Steven She Scala Growing a Language 543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 13: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 14: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 15: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Programming in a Bazaar

Framework code should appear indistinguishablefrom native language features

Something likehellipScheme

Scala is a practical language that enables users togrow the language in a seamless manner

Steven She Scala Growing a Language 643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 16: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 17: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Lets talk about Scala

Scala gt Java

Topic for this talkWhat language constructs does Scala providethat enable a user to grow the language

Steven She Scala Growing a Language 743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 18: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 19: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 20: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 21: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 22: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton

Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 23: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method Declaration

Parameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip) Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 24: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 25: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Hello world

Singleton Method DeclarationParameter Declaration

object HelloWorld def main( args Array[String]) Unit =

println(Hello world)

Predefprintln(hellip)

Return type

Steven She Scala Growing a Language 1043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 26: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 27: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 28: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 29: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 30: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Basic Method Declarations

object HelloWorld def simple String =

Hello World

def verbose() String = return Hello World

def ++() String = val str = Hello World str

def infer = Hello World

Steven She Scala Growing a Language 1143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 31: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 32: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 33: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 34: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Type Less With Type Inference

def infer = Hello World returns String

val strList =a b c Nil List[String]

val intList =1 2 3 Nil List[Int]

val anyList =1 b c Nil List[Any]

Steven She Scala Growing a Language 1243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 35: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 36: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 37: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 38: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Operators are Method Calls

w ampamp x || y ampamp z larrrarr ( wampamp(x) )||( (y)ampamp(z) )

Right-associative operators are defined with as a suffix

a b c NilNil(c)(b)(a)

Primitives in Java are treated as objects in Scala

intrarr scalaIntbooleanrarr scalaBoolean

hellip

Steven She Scala Growing a Language 1343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 39: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 40: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Objects Classes and Traits

Singletons (object)No statics in Scala Singletons can be referenced andassigned

ClassesSame as in Java But they can mix in multiple traits

TraitsSimilar to a Java interface but with default implementationA form of mixinwhere a trait is merged into a base class

Steven She Scala Growing a Language 1443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 41: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 42: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 43: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter

Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 44: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 45: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 46: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Comparison Trait

trait Ordered[ A] def lt (that A) Boolean def lt=(that A) = (this lt that) || (this ==

that)

def gt (that A) = (this lt= that)def gt=(that A) = (this lt that)

class ComplexNumber(val real Int val img Int)extends Number(real) with Ordered[ComplexNumber]

def lt (that ComplexNumber) = real lt thatreal ||real == thatreal ampamp (img lt thatimg)

Type Parameter Abstract Method

Pre-defined equals method

Boolean operators

0httpwwwscala-langorgdocufilesScalaTutorialpdf

Steven She Scala Growing a Language 1543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 47: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 48: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Logging Trait

import orgslf4jLogger LoggerFactory

trait Logging private val log = LoggerFactorygetLogger(getClass)

def debug(msgString eThrowable) = logdebug(msg e)hellip

class ComplexNumber(real Int img Int) extends Number(real)with Ordered[ComplexNumber] with Logging

hellipdebug(Error occurred e)

0httpjohlroggewordpresscom20090627loggingtools-in-scala

Steven She Scala Growing a Language 1643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 49: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 1743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 50: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 51: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Java Maps

MapltString Stringgt capitals = new HashMapltString Stringgt()

capitalsput(Ontario Toronto)capitalsput(Quebec Quebec City)capitalsput(BC Victoria)

String toronto = capitalsget(Ontario)String unknown = capitalsget(123) returns null

bull Map implementation is explicitly instantiatedbull Mapmust be initialized separately (mutable)bull Retrieving an absent key returns null

Steven She Scala Growing a Language 1843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 52: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 53: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps

val capitals = Map(Ontario -gt TorontoQuebec -gt Quebec CityBC -gt Victoria)

bull Immutable associative mapbull Written using no special keywords or syntaxbull Uses implicit methods and operator methods

Steven She Scala Growing a Language 1943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 54: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 55: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 56: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 57: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 58: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 59: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 60: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 61: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 62: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int]

Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 63: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 64: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 65: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Aside Folding

Returns a List[Int] Anonymous function

(0 ( 1 until 10))( (sumnum) =gt sum + num )

(1 until 10)foldLeft(0)( (sumnum) =gt sum + num )

var sum = 0for (num lt- 1 until 10)

sum = sum + num

(0 (1 until 10))( _ + _ )

+

+

0 (base) 1

2

Steven She Scala Growing a Language 2143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 66: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 67: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 68: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Map Factory

Map(Ontario -gt Toronto)object Map

def apply[A B](elems (A B)) = empty[A B] ++ elemsdef empty[A B] Map[A B] = new EmptyMap[A B]

trait Map[A +B] extends hellip def ++ [B1 gt B] (kvs Iterable[(A B1)]) Map[A B1] =

((this Map[A B1]) kvs) ((m kv) =gt m + kv)

def + [B1 gt B] (kv (A B1)) Map[A B1] =update(kv_1 kv_2)

Steven She Scala Growing a Language 2243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 69: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 70: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Specializing the Map

class EmptyMap[] extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

new Map1(key value)

class Map1 extends Map[] def update [B1 gt B](key A value B1) Map[A B1] =

if (key == key1) new Map1(key1 value)else new Map2(key1 value1 key value)

bull More efficient than just a Hash Mapbull Factory pattern is built into the language

Steven She Scala Growing a Language 2343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 71: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 72: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 73: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString

-gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 74: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 75: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 76: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Arrow on a String

Map( Ontario -gt( Toronto ))

javalangString -gt method

bull hellipbut javalangString doesnt have a -gtmethodbull enter implicit methods

Steven She Scala Growing a Language 2443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 77: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 78: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 79: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 80: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 81: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods

DefinitionAn implicit method is automatically called when an object of typeA is called but an object of type B is required

implicit def str2int( s String) Int= IntegerparseInt(s)

def addOne( num Int) = num + 1

val result = addOne( 1)println(result)

Steven She Scala Growing a Language 2543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 82: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 83: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 84: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 85: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Implicit Methods (cont)

Implicit methods could also be used to introduce newmethods into existing classes

class PigLatin(x String) def pigSpeak = xsubstring(1) + - + x(0) + ay

implicit def str2pigLatin(s String)= new PigLatin(s)

println( hellopigSpeak ) outputs ello-hay

Steven She Scala Growing a Language 2643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 86: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 87: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 88: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 89: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 90: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 91: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Adding an Arrow to String

Map(Ontario -gt Toronto)

class ArrowAssoc[A](x A) def -gt [B](y B) Tuple2[A B] = (x y)

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

bull Ontario-gt(Toronto)bull rarr new ArrowAssoc(Ontario)-gt(Toronto))bull rarr (Ontario Toronto)

Steven She Scala Growing a Language 2743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 92: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 93: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Retrieving Values fromMapsval toronto = capitalsget(Ontario) Some(Toronto)val unknown = capitalsget(123) None

trait Map[A B] abstract def get(key A) Option[B]hellip

Option[A]

None[Nothing] Some[A]val x A

Steven She Scala Growing a Language 2843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 94: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 95: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 96: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Pattern Matching on Objects

val retrieve = capitalsget(Nunavut)

retrieve match case Some(x) =gt println(Found + x)case None =gt println(Unknown)

println(retrieve match case Some(x) =gt Found + xcase None =gt Unknown

)

Steven She Scala Growing a Language 2943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 97: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 98: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 99: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 100: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 101: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Co-Variance

trait Map[A +B]

Map[String Any]

Map[String Int] Map[String String]

val strMap = Map(Foo -gt Bar) Map[String String]val intMap = Map(One -gt 1) Map[String Int]val mergedMap = strMap ++ intMap Map[String Any]

Steven She Scala Growing a Language 3043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 102: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Associative Maps Conclusion

bull Factory pattern built into languagebull Provide cleaner syntax through operator methodsbull Added methods to String using implicit conversionbull Co-variance defines subtyping based on a type parameterbull Get method returns Option which preventsNullPointerExceptions

bull Framework complexity is hidden from the user

Steven She Scala Growing a Language 3143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 103: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 104: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Scalas Type System

Everything is an object

Any

AnyRefAnyVal

hellip helliprepresents primitive types represents objects

0httpprogramming-scalalabsoreillycomch07htmlscalas-type-hierarchy

Steven She Scala Growing a Language 3343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 105: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyRef Type Hierarchy

AnyRef

ScalaObject

Java types scala types

Null

Steven She Scala Growing a Language 3443

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 106: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

AnyVal Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

Steven She Scala Growing a Language 3543

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 107: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Combined Type Hierarchy

AnyVal

Unit Double

FloatBoolean

IntChar

AnyRef

ScalaObject

Java types scala types

Null

Any

Nothing

Steven She Scala Growing a Language 3643

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 108: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 3743

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 109: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Baysickobject Lunar extends Baysick

def main(argsArray[String]) = 10 PRINT Welcome to Baysick Lunar Lander v0920 LET (dist = 100)30 LET (v = 1)40 LET (fuel = 1000)50 LET (mass = 1000)

hellip

100 PRINT Distance dist km Velocity hellip110 INPUT burn120 IF ABS(burn) lt= fuel THEN 150130 PRINT You dont have that much fuel140 GOTO 100

hellip0httpblogfogusme20090326baysick-a-scala-dsl-implementing-basic

Steven She Scala Growing a Language 3843

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 110: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 111: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Parser Combinators

BNFexpr = term (+ term | - term)term = factor ( factor | factor)factor = floatingPointNumber | ( expr )

Scalaobject ArithParser extends JavaTokenParsers

def expr Parser[Any] = term ~ (+ ~ term | - ~ term)def term = factor ~ ( ~ factor | ~ factor)def factor = floatingPointNumber | ( ~ expr ~ )

def parse(text String) = parseAll(expr text)

0httpwwwibmcomdeveloperworksjavalibraryj-scala10248html

Steven She Scala Growing a Language 3943

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 112: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Outline

1 Basics

2 Scala Maps

3 Type System

4 DSLs

5 Conclusions

Steven She Scala Growing a Language 4043

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 113: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Conclusions

bull Static type system gives us type safetybull Type inference can save a lot of typingbull Everything is an objectbull Operators are just method callsbull Implicit methods used hellip

bull for automatic type conversionbull to introduce newmethods

bull Pattern Matching

Steven She Scala Growing a Language 4143

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 114: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 115: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 116: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Ambiguous implicit methods

implicit def any2ArrowAssoc[A](x A)= new ArrowAssoc(x)

class ArrowAssoc[A](x A) def -gt [B](y B) =

implicit def any2MyArrow[A](x A)= new MyArrow(x)

class MyArrow(x Any) def -gt (y MyClassB) =

Steven She Scala Growing a Language 4243

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 117: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 118: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 119: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra
Page 120: Scala: Growing a Languagestevenshe.ca/assets/files/slides-scala2008.pdf · Introduction Outline Basics ScalaMaps TypeSystem DSLs Conclusions Extra Scala: GrowingaLanguage StevenShe

Introduction Outline Basics Scala Maps Type System DSLs Conclusions Extra

Dangers of implicit conversions

radar == radarreverserArr false

String RichString

bull Bug in current version of Scalabull comparing String and RichString using equals (==) returnsfalse

bull Conversion of types happens behind-your-back

Steven She Scala Growing a Language 4343

  • Introduction
  • Outline
  • Basics
  • Scala Maps
  • Type System
  • DSLs
  • Conclusions
  • Extra