• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scala
 

Scala

on

  • 6,437 views

 

Statistics

Views

Total Views
6,437
Views on SlideShare
6,422
Embed Views
15

Actions

Likes
19
Downloads
0
Comments
0

5 Embeds 15

http://www.slideshare.net 7
http://www.linkedin.com 3
http://localhost 3
http://webcache.googleusercontent.com 1
https://twitter.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Scala Scala Presentation Transcript

    • 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