SlideShare a Scribd company logo
1 of 38
Scala
An Introduction by Sven Efftinge (itemis AG)
What is Scala?

• Object oriented (no primitives)
• functional
• runs on Java Virtual Machine
• interpreter available
• statically typed
History


• Designed by Martin Odersky
• Developed at EPFL (Switzerland)
object hello {
  def main(args:Array[String])=
    println(quot;Hello Worldquot;)
}
package SwingDemo
import javax.swing.{JFrame, JLabel}

object Main extends Application {
  def getTitle() = “Scala can Swing”

    val frm = new JFrame(getTitle)
    frm.getContentPane.add(
                   new JLabel(“Hello World”))
    frm.setDefaultCloseOperation(
                   JFrame.EXIT_ON_CLOSE)
    frm.pack
    frm setVisible true
}
scala.Any




                                                                                                                                      scala.AnyRef
                               scala.AnyVal
                                                                                                                                   (java.lang.Object)


                                                                                                    scala.ScalaObject
scala.Double

                                                      scala.Unit
   scala.Float

                                                 scala.Boolean
       scala.Long                                                                        scala.Seq
                                                                                                                                                                   Java.lang.String
                                              scala.Char
           scala.Int                                                                                  scala.List

                                                                                                                                                 ... other Java types ...
               scala.Short                                                                                         scala.Option


                  scala.Byte
                                                                                                                              ... other Scala types ...




                                                                                       scala.Null




                                                           scala.Nothing
No statements,
      just expressions
• Everything returns something
• for, while and if/else are expressions
• Unit is the equivalent to Java’s void
• Explicit return is optional:
  def plus2(x:Int) = x+2
def foo(arg:String)={
  if (arg==null) {
    throw new RuntimeException(“Ups”)
  } else {
    “foobar”
  }
}

def foo(arg:String): String ={
  if (arg!=null) {
    throw new RuntimeException(“Ups”)
  } else {
    return “foobar”
  }
}
Vals and Vars
def foo() {
  val x = “immutable”
  // Java: final x
  var y = “mutable”
}
“Operator Overloading”

class Foo(value:Int) {
  def +(other:Foo) = value + other.value
}

val foo = new Foo(13)
val foo2 = new Foo(23)
println(foo + foo2) // outputs “36”
println(foo.+(foo2)) // outputs “36”
class Foo(val value:Int) {
  def unary_! = quot;!!!quot; + value + quot;!!!quot;
  def *:(multiple:Int) = value * multiple
}

var foo = new Foo(62)

!foo      // result: String = “!!!62!!!”
foo.!()   // the same

2 *: foo // result: Int = 124
foo.*:(2)// the same
apply()
class Foo(value:Int) {
  def apply(op:Int) = value*op
}
val foo = new Foo(42)
foo(2) // results in 84
Constructors
class Foo(val immutable:String,
          var mutable:String)

var f = new   Foo(“foo”,”bar”)
f.immutable   == f.mutable //false
f.mutable =   “foo”
f.immutable   == f.mutable //true
Properties
class AbsoluteNumber(num:Int) {
  private var _value = Math.abs(num)
  def value = _value
  def value_=(num:Int) =
     _value = Math.abs(num)
}
Traits
• Like interfaces in Java, but
 • can have implementations
 • can have fields
Traits
trait Ordered[A] {

    def compare(that: A): Int

    def   <    (that:   A)   =   (this   compare   that)< 0
    def   >    (that:   A)   =   (this   compare   that)> 0
    def   <=   (that:   A)   =   (this   compare   that)<=0
    def   >=   (that:   A)   =   (this   compare   that)>=0

}
class   Animal
trait   Furry extends Animal
trait   FourLegged extends Animal with HasLegs
trait   HasLegs extends Animal
class   Cat extends Animal with Furry with FourLegged
Mixing in during
          construction
trait Foo {
  def foo(text:String) =
    println(text+toString)
}
class Now {
  override def toString =
    new java.util.Date().toString()
}

val now = new Now with Foo
now foo “It’s ” // “It’s <current time>“
implicits
 implicit def stringWrapper(s: String) =
 new RandomAccessSeq[Char] {
   def length = s.length
   def apply(i: Int) = s.charAt(i)
 }

quot;abc123quot; exists (_.isDigit)

stringWrapper(quot;abc123quot;) exists (_.isDigit)
Rich Wrappers
scala> 42 max 43
res7: Int = 43
scala> 42 min 43
res8: Int = 42
scala> 1 until 5
res9: Range = Range(1, 2, 3, 4)
scala> 1 to 5
res10: Range.Inclusive = Range(1, 2, 3, 4, 5)
scala> 3.abs
res11: Int = 3
scala> (-3).abs
res12: Int = 3
Functional Programming


Functions as Values
No side effects (purity)
Has it’s roots in Alonzo Church’s
“Lambda Calculus”
Lisp, Scheme, SML, Erlang, Haskell,
OCaml, F#
Functions as Objects

val multiply = (x:Int, y:Int) => x * y
val altMulti:(Int,Int)=>Int = _ * _
    multiply(2,3) == altMulti(2,3)
Higher-order Functions


def timeBlock(block: =>Unit) {
  val start = System.currentTimeMillis()
  block
  printf(quot;Block took {0} millisecondsnquot;,
    System.currentTimeMillis - start)
}

timeBlock {
  (1 to 4).foreach{x => println(quot;x = quot;+x)}
}
Currying and Loan Pattern


def using[A](r : File)
             (f : InputStream => A) : A {
    val in = getStream(r)
    try {
        f(in)
    } finally {
        in.close()
    }
}
using(myRes) { in =>
   in.read()
}
Closures make ...

... querying Structures easier
and creation of
new control structures possible
Lists

val xs = List(1,2,3)
xs.map(_ * 2)         //   List(2,4,6)
val xs1 = 0::xs       //   List(0,1,2,3)
val xs2 = xs1 ::: xs //    List(0,1,2,3,1,2,3)
xs2.filter(_ % 2 == 1)//   List(1,3,1,3)

xs2.head             // 0
xs2.tail             // List(1,2,3,1,2,3)
Tuples

val pair = (99, quot;Luftballonsquot;)
println(pair._1)
println(pair._2)
// type is Tuple2[Int, String]
Case Classes
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr)
  extends Expr
case class BinOp(left: Expr,
  operator: String, right: Expr) extends Expr
Case Classes (2)

val expr =
   BinOp(Number(2), “*”, UnOp(“-”,Var(“x”))

def simplify(expr: Expr) = expr match {
  case UnOp(quot;-quot;, UnOp(quot;-quot;, e)) => e
  case BinOp(e, quot;+quot;, Number(0)) => e
  case BinOp(e, quot;*quot;, Number(1)) => e
  case _ => expr
}
Pattern Matching (1)

def describe(x: Any) = x match {
  case 5 => quot;fivequot;
  case true => quot;truthquot;
  case quot;helloquot; => quot;hi!quot;
  case Nil => quot;the empty listquot;
  case _ => quot;something elsequot;
}
Pattern Matching (2)

def describe(x: Any) = x match {
  case x::xs => “head:”+x+” tail:”+xs
  case List(1,_*,2) => quot;a special listquot;
  case (_,quot;helloquot;) => quot;hi tuple!quot;
  case _ => quot;something elsequot;
}
Extractors
object EMail {
  def unapply(str:String):Option((String,String))={
    val parts = str split quot;@quot;
    if (parts.length == 2)
      Some(parts(0), parts(1))
    else
      None
  }
}

def isAllowed(email:String) = {
  email match {
    case Email(alias,”web.de”) => false
    case _ => true
  }
}
For-Expressions

case class Person(name: String,
                  isMale: Boolean,
                  children: Person*)

val   lara =    Person(quot;Laraquot;, false)
val   bob   =   Person(quot;Bobquot;, true)
val   julie =   Person(quot;Juliequot;, false, lara, bob)
val   persons   = List(lara, bob, julie)

for (p <- persons)
  println(p.name)
Finding pairs of
mother and kid in Java

List<Pair> result = new ArrayList<Pair>();
for(Person p : persons) {
  if (!p.isMale()) {
    for(Person c: p.children) {
      result.add(
        new Pair(p.getName(),c.getName()));
    }
  }
}
In Scala using
higher-order functions


persons filter (p => !p.isMale)
       flatMap (p =>
         (p.children map (c =>
             (p.name, c.name))))
In Scala using
for-expression


for (p <- persons;
     if (!p.isMale);
     c <- p.children)
  yield (p.name, c.name)
More to look at...
• Type Parameterization
• XML literals
• Combining Java and Scala
  (In short: Calling Java from Scala is straight
  forward, but the other way round needs a
  little bit of thinking)
• Actor library
• Combinator parser library
www.scala-lang.org

Artima's Scalazine online
magazine
www.artima.com/
scalazine

Lift – Web framework written
in Scala:
www.liftweb.net

More Related Content

What's hot

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheoryKnoldus Inc.
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scalaakuklev
 

What's hot (16)

Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
All about scala
All about scalaAll about scala
All about scala
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scala test
Scala testScala test
Scala test
 

Similar to Scala Introduction - Object Oriented, Functional Programming Language for JVM

Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Erik Schmiegelow
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaBrian Hsu
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD Sayem Ahmed
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 

Similar to Scala Introduction - Object Oriented, Functional Programming Language for JVM (20)

Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala intro for Java devs 20150324
Scala intro for Java devs 20150324Scala intro for Java devs 20150324
Scala intro for Java devs 20150324
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala
ScalaScala
Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 

More from Sven Efftinge

Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With XtextSven Efftinge
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With XtextSven Efftinge
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendSven Efftinge
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven Efftinge
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With XtendSven Efftinge
 
Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Sven Efftinge
 
Xtend @ EclipseCon 2012
Xtend @ EclipseCon 2012Xtend @ EclipseCon 2012
Xtend @ EclipseCon 2012Sven Efftinge
 
This Is Not Your Father's Java
This Is Not Your Father's JavaThis Is Not Your Father's Java
This Is Not Your Father's JavaSven Efftinge
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Sven Efftinge
 
Xtext at MDD Day 2010
Xtext at MDD Day 2010Xtext at MDD Day 2010
Xtext at MDD Day 2010Sven Efftinge
 
Dependency Injection for Eclipse developers
Dependency Injection for Eclipse developersDependency Injection for Eclipse developers
Dependency Injection for Eclipse developersSven Efftinge
 
Challenges In Dsl Design
Challenges In Dsl DesignChallenges In Dsl Design
Challenges In Dsl DesignSven Efftinge
 
Code Generation in Agile Projects
Code Generation in Agile ProjectsCode Generation in Agile Projects
Code Generation in Agile ProjectsSven Efftinge
 

More from Sven Efftinge (20)

Parsing Expression With Xtext
Parsing Expression With XtextParsing Expression With Xtext
Parsing Expression With Xtext
 
Language Engineering With Xtext
Language Engineering With XtextLanguage Engineering With Xtext
Language Engineering With Xtext
 
Future of Xtext
Future of XtextFuture of Xtext
Future of Xtext
 
Auto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with XtendAuto-GWT : Better GWT Programming with Xtend
Auto-GWT : Better GWT Programming with Xtend
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
Codegeneration With Xtend
Codegeneration With XtendCodegeneration With Xtend
Codegeneration With Xtend
 
Gwt and Xtend
Gwt and XtendGwt and Xtend
Gwt and Xtend
 
Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)Domain Specific Languages (EclipseCon 2012)
Domain Specific Languages (EclipseCon 2012)
 
Xtend @ EclipseCon 2012
Xtend @ EclipseCon 2012Xtend @ EclipseCon 2012
Xtend @ EclipseCon 2012
 
Eclipse Xtend
Eclipse XtendEclipse Xtend
Eclipse Xtend
 
This Is Not Your Father's Java
This Is Not Your Father's JavaThis Is Not Your Father's Java
This Is Not Your Father's Java
 
Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]Getting the most out of Java [Nordic Coding-2010]
Getting the most out of Java [Nordic Coding-2010]
 
Xtext at MDD Day 2010
Xtext at MDD Day 2010Xtext at MDD Day 2010
Xtext at MDD Day 2010
 
Dependency Injection for Eclipse developers
Dependency Injection for Eclipse developersDependency Injection for Eclipse developers
Dependency Injection for Eclipse developers
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Challenges In Dsl Design
Challenges In Dsl DesignChallenges In Dsl Design
Challenges In Dsl Design
 
Code Generation in Agile Projects
Code Generation in Agile ProjectsCode Generation in Agile Projects
Code Generation in Agile Projects
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Generic Editor
Generic EditorGeneric Editor
Generic Editor
 
Eclipse Banking Day
Eclipse Banking DayEclipse Banking Day
Eclipse Banking Day
 

Scala Introduction - Object Oriented, Functional Programming Language for JVM

  • 1. Scala An Introduction by Sven Efftinge (itemis AG)
  • 2. What is Scala? • Object oriented (no primitives) • functional • runs on Java Virtual Machine • interpreter available • statically typed
  • 3. History • Designed by Martin Odersky • Developed at EPFL (Switzerland)
  • 4. object hello { def main(args:Array[String])= println(quot;Hello Worldquot;) }
  • 5. package SwingDemo import javax.swing.{JFrame, JLabel} object Main extends Application { def getTitle() = “Scala can Swing” val frm = new JFrame(getTitle) frm.getContentPane.add( new JLabel(“Hello World”)) frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) frm.pack frm setVisible true }
  • 6. scala.Any scala.AnyRef scala.AnyVal (java.lang.Object) scala.ScalaObject scala.Double scala.Unit scala.Float scala.Boolean scala.Long scala.Seq Java.lang.String scala.Char scala.Int scala.List ... other Java types ... scala.Short scala.Option scala.Byte ... other Scala types ... scala.Null scala.Nothing
  • 7. No statements, just expressions • Everything returns something • for, while and if/else are expressions • Unit is the equivalent to Java’s void • Explicit return is optional: def plus2(x:Int) = x+2
  • 8. def foo(arg:String)={ if (arg==null) { throw new RuntimeException(“Ups”) } else { “foobar” } } def foo(arg:String): String ={ if (arg!=null) { throw new RuntimeException(“Ups”) } else { return “foobar” } }
  • 9. Vals and Vars def foo() { val x = “immutable” // Java: final x var y = “mutable” }
  • 10. “Operator Overloading” class Foo(value:Int) { def +(other:Foo) = value + other.value } val foo = new Foo(13) val foo2 = new Foo(23) println(foo + foo2) // outputs “36” println(foo.+(foo2)) // outputs “36”
  • 11. class Foo(val value:Int) { def unary_! = quot;!!!quot; + value + quot;!!!quot; def *:(multiple:Int) = value * multiple } var foo = new Foo(62) !foo // result: String = “!!!62!!!” foo.!() // the same 2 *: foo // result: Int = 124 foo.*:(2)// the same
  • 12. apply() class Foo(value:Int) { def apply(op:Int) = value*op } val foo = new Foo(42) foo(2) // results in 84
  • 13. Constructors class Foo(val immutable:String, var mutable:String) var f = new Foo(“foo”,”bar”) f.immutable == f.mutable //false f.mutable = “foo” f.immutable == f.mutable //true
  • 14. Properties class AbsoluteNumber(num:Int) { private var _value = Math.abs(num) def value = _value def value_=(num:Int) = _value = Math.abs(num) }
  • 15. Traits • Like interfaces in Java, but • can have implementations • can have fields
  • 16. Traits trait Ordered[A] { def compare(that: A): Int def < (that: A) = (this compare that)< 0 def > (that: A) = (this compare that)> 0 def <= (that: A) = (this compare that)<=0 def >= (that: A) = (this compare that)>=0 }
  • 17. class Animal trait Furry extends Animal trait FourLegged extends Animal with HasLegs trait HasLegs extends Animal class Cat extends Animal with Furry with FourLegged
  • 18. Mixing in during construction trait Foo { def foo(text:String) = println(text+toString) } class Now { override def toString = new java.util.Date().toString() } val now = new Now with Foo now foo “It’s ” // “It’s <current time>“
  • 19. implicits implicit def stringWrapper(s: String) = new RandomAccessSeq[Char] { def length = s.length def apply(i: Int) = s.charAt(i) } quot;abc123quot; exists (_.isDigit) stringWrapper(quot;abc123quot;) exists (_.isDigit)
  • 20. Rich Wrappers scala> 42 max 43 res7: Int = 43 scala> 42 min 43 res8: Int = 42 scala> 1 until 5 res9: Range = Range(1, 2, 3, 4) scala> 1 to 5 res10: Range.Inclusive = Range(1, 2, 3, 4, 5) scala> 3.abs res11: Int = 3 scala> (-3).abs res12: Int = 3
  • 21. Functional Programming Functions as Values No side effects (purity) Has it’s roots in Alonzo Church’s “Lambda Calculus” Lisp, Scheme, SML, Erlang, Haskell, OCaml, F#
  • 22. Functions as Objects val multiply = (x:Int, y:Int) => x * y val altMulti:(Int,Int)=>Int = _ * _ multiply(2,3) == altMulti(2,3)
  • 23. Higher-order Functions def timeBlock(block: =>Unit) { val start = System.currentTimeMillis() block printf(quot;Block took {0} millisecondsnquot;, System.currentTimeMillis - start) } timeBlock { (1 to 4).foreach{x => println(quot;x = quot;+x)} }
  • 24. Currying and Loan Pattern def using[A](r : File) (f : InputStream => A) : A { val in = getStream(r) try { f(in) } finally { in.close() } } using(myRes) { in => in.read() }
  • 25. Closures make ... ... querying Structures easier and creation of new control structures possible
  • 26. Lists val xs = List(1,2,3) xs.map(_ * 2) // List(2,4,6) val xs1 = 0::xs // List(0,1,2,3) val xs2 = xs1 ::: xs // List(0,1,2,3,1,2,3) xs2.filter(_ % 2 == 1)// List(1,3,1,3) xs2.head // 0 xs2.tail // List(1,2,3,1,2,3)
  • 27. Tuples val pair = (99, quot;Luftballonsquot;) println(pair._1) println(pair._2) // type is Tuple2[Int, String]
  • 28. Case Classes abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(left: Expr, operator: String, right: Expr) extends Expr
  • 29. Case Classes (2) val expr = BinOp(Number(2), “*”, UnOp(“-”,Var(“x”)) def simplify(expr: Expr) = expr match { case UnOp(quot;-quot;, UnOp(quot;-quot;, e)) => e case BinOp(e, quot;+quot;, Number(0)) => e case BinOp(e, quot;*quot;, Number(1)) => e case _ => expr }
  • 30. Pattern Matching (1) def describe(x: Any) = x match { case 5 => quot;fivequot; case true => quot;truthquot; case quot;helloquot; => quot;hi!quot; case Nil => quot;the empty listquot; case _ => quot;something elsequot; }
  • 31. Pattern Matching (2) def describe(x: Any) = x match { case x::xs => “head:”+x+” tail:”+xs case List(1,_*,2) => quot;a special listquot; case (_,quot;helloquot;) => quot;hi tuple!quot; case _ => quot;something elsequot; }
  • 32. Extractors object EMail { def unapply(str:String):Option((String,String))={ val parts = str split quot;@quot; if (parts.length == 2) Some(parts(0), parts(1)) else None } } def isAllowed(email:String) = { email match { case Email(alias,”web.de”) => false case _ => true } }
  • 33. For-Expressions case class Person(name: String, isMale: Boolean, children: Person*) val lara = Person(quot;Laraquot;, false) val bob = Person(quot;Bobquot;, true) val julie = Person(quot;Juliequot;, false, lara, bob) val persons = List(lara, bob, julie) for (p <- persons) println(p.name)
  • 34. Finding pairs of mother and kid in Java List<Pair> result = new ArrayList<Pair>(); for(Person p : persons) { if (!p.isMale()) { for(Person c: p.children) { result.add( new Pair(p.getName(),c.getName())); } } }
  • 35. In Scala using higher-order functions persons filter (p => !p.isMale) flatMap (p => (p.children map (c => (p.name, c.name))))
  • 36. In Scala using for-expression for (p <- persons; if (!p.isMale); c <- p.children) yield (p.name, c.name)
  • 37. More to look at... • Type Parameterization • XML literals • Combining Java and Scala (In short: Calling Java from Scala is straight forward, but the other way round needs a little bit of thinking) • Actor library • Combinator parser library