Your SlideShare is downloading. ×
Scala
An Introduction by Sven Efftinge (itemis AG)
What is Scala?

• Object oriented (no primitives)
• functional
• runs on Java Virtual Machine
• interpreter available
• st...
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 Swi...
scala.Any




                                                                                                            ...
No statements,
      just expressions
• Everything returns something
• for, while and if/else are expressions
• Unit is th...
def foo(arg:String)={
  if (arg==null) {
    throw new RuntimeException(“Ups”)
  } else {
    “foobar”
  }
}

def foo(arg:...
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 ...
class Foo(val value:Int) {
  def unary_! = quot;!!!quot; + value + quot;!!!quot;
  def *:(multiple:Int) = value * multiple...
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   =...
Properties
class AbsoluteNumber(num:Int) {
  private var _value = Math.abs(num)
  def value = _value
  def value_=(num:Int...
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
    ...
class   Animal
trait   Furry extends Animal
trait   FourLegged extends Animal with HasLegs
trait   HasLegs extends Animal
...
Mixing in during
          construction
trait Foo {
  def foo(text:String) =
    println(text+toString)
}
class Now {
  ov...
implicits
 implicit def stringWrapper(s: String) =
 new RandomAccessSeq[Char] {
   def length = s.length
   def apply(i: I...
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...
Functional Programming


Functions as Values
No side effects (purity)
Has it’s roots in Alonzo Church’s
“Lambda Calculus”
...
Functions as Objects

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


def timeBlock(block: =>Unit) {
  val start = System.currentTimeMillis()
  block
  printf(quot;Blo...
Currying and Loan Pattern


def using[A](r : File)
             (f : InputStream => A) : A {
    val in = getStream(r)
   ...
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 ...
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
cas...
Case Classes (2)

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

def simplify(expr: Expr) = expr match {
  case U...
Pattern Matching (1)

def describe(x: Any) = x match {
  case 5 => quot;fivequot;
  case true => quot;truthquot;
  case qu...
Pattern Matching (2)

def describe(x: Any) = x match {
  case x::xs => “head:”+x+” tail:”+xs
  case List(1,_*,2) => quot;a...
Extractors
object EMail {
  def unapply(str:String):Option((String,String))={
    val parts = str split quot;@quot;
    if...
For-Expressions

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

...
Finding pairs of
mother and kid in Java

List<Pair> result = new ArrayList<Pair>();
for(Person p : persons) {
  if (!p.isM...
In Scala using
higher-order functions


persons filter (p => !p.isMale)
       flatMap (p =>
         (p.children map (c =...
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 ...
www.scala-lang.org

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

Lift – Web framework written
in Scala:
w...
Upcoming SlideShare
Loading in...5
×

Scala

4,756

Published on

Transcript of "Scala"

  1. 1. Scala An Introduction by Sven Efftinge (itemis AG)
  2. 2. What is Scala? • Object oriented (no primitives) • functional • runs on Java Virtual Machine • interpreter available • statically typed
  3. 3. History • Designed by Martin Odersky • Developed at EPFL (Switzerland)
  4. 4. object hello { def main(args:Array[String])= println(quot;Hello Worldquot;) }
  5. 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. 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. 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. 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. 9. Vals and Vars def foo() { val x = “immutable” // Java: final x var y = “mutable” }
  10. 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. 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. 12. apply() class Foo(value:Int) { def apply(op:Int) = value*op } val foo = new Foo(42) foo(2) // results in 84
  13. 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. 14. Properties class AbsoluteNumber(num:Int) { private var _value = Math.abs(num) def value = _value def value_=(num:Int) = _value = Math.abs(num) }
  15. 15. Traits • Like interfaces in Java, but • can have implementations • can have fields
  16. 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. 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. 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. 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. 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. 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. 22. Functions as Objects val multiply = (x:Int, y:Int) => x * y val altMulti:(Int,Int)=>Int = _ * _ multiply(2,3) == altMulti(2,3)
  23. 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. 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. 25. Closures make ... ... querying Structures easier and creation of new control structures possible
  26. 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. 27. Tuples val pair = (99, quot;Luftballonsquot;) println(pair._1) println(pair._2) // type is Tuple2[Int, String]
  28. 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. 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. 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. 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. 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. 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. 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. 35. In Scala using higher-order functions persons filter (p => !p.isMale) flatMap (p => (p.children map (c => (p.name, c.name))))
  36. 36. In Scala using for-expression for (p <- persons; if (!p.isMale); c <- p.children) yield (p.name, c.name)
  37. 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
  38. 38. www.scala-lang.org Artima's Scalazine online magazine www.artima.com/ scalazine Lift – Web framework written in Scala: www.liftweb.net

×