KEMBAR78
Scala - brief intro | PPT
Strengths of Scala Java replacement? The answer doesn’t matter! Brief intro to Scala - Razvan Cojocaru – Nov’08 & Mar’09
Overview Brief syntax – at least 30% off Java Smart compiler != dumb programmer Compiles into bytecode, runs on JVM    access to all Java libraries and, more importantly, APIs C++ is back! …mean as ever! Multiple inheritance, operator overloading, true generics, pass functions around, simple syntax Scala is better: true multi-paradigm Functional programming Scalable language Not for the faint of heart!
Smart Compiler Makes up constructors, getX/setX stuff class Point (x:Int,y:Int) Figures out types for values/variables and functions etc def getX = x Lots of shortcuts in the syntax, i.e no {} for method bodies
Smart compiler != dumb programmer Class Point { int x; int y; public Point (int ax, int ay) { this.x = ax; this.y = ay; } public int getX () { return x; } public int getY () { return y; } public int setX (int x) {  if (x <= 0)  throw new IllegalArgumentException(“blah”); else this.x=x } public int setY (int y) { this.y=y } } Class Point ( var  x:int, var y:int) def  x_= (ax:Int) =  require  (ax > 0); x=ax To overwrite the assign, is actually a little more complicated: def   +  (p:Point) =  new Point (x+p.x, y+p.y) Guess who ^^^ Guess who ^^^
Constructor/field generation class  SimplerPoint ( private   var   ix  : Int,  private   var   iy :Int)  { def  x =  ix def  y =  iy def  x_= ( ax :Int) { require( ax >0);  ix = ax  } def  y_= ( ay :Int) { require( ay >0);  iy = ay  } } class Point (ax:Int, ay:Int) { private[this] var  ix :Int = ax private[this] var  iy :Int = ay def x =  ix def y =  iy def x_= (ax:Int) { require(ax>0);  ix =ax } def y_= (ay:Int) { require(ay>0);  iy =ay } } // check this out !!! class Point (ax:Int, ay:Int) { require(ax>0); // class body is in fact c-tor private[this] var  ix :Int = ax def x_= (ax:Int) { require(ax>0);  ix =ax } } Ix/iy are both constructor and fields Classic: ax/ay are just args for constructor
Traits Like multiple inheritance More like “polymorphic composition”…if that pairing makes sense   Simplify coding a lot, for classes with multiple “traits”. No interfaces There are abstract classes, though An abstract trait (all methods abstract) is equivalent to a Java interface
Traits - features As opposed to interfaces, traits can implement methods No “controllers” etc No replication of code. With single inheritance, you decide on a base class and then REWRITE every time the methods of other implemented interfaces “ idiot controller” syndrome: keep algorthms in different classes, to avoid rewriting them, see next slide TODO: read about the “linearization” to avoid diamond inheritance Same as “mixin” in Ruby Trait vs. Class ?  Semantics …
Traits vs interfaces interface Centered { public Point getCenter () { return x; } } class IdiotController { public void offset (Centered s, Point offsetBy) {…} } class MyShape extends Drawable implements Centered { //… public Point getCenter () { return c; } } //…in a java file far far away: New IdiotController().offset (myShape, new Point (3,4)) trait  Centered () { var  center:Point def offset (offsetBy:Point) = center += offsetBy } Class MyShape extends Drawable with Centered { } //…in a scala file anywereh in the galaxy myShape.offset ((3,4)) Guess who ^^^ Guess who ^^^
The screwyness of it trait AnotherCentered { def  center:Point def offset (offsetBy:Point) = center += offsetBy } class AnotherShape extends AnotherCentered { override   val  center:Point = new Point(0,0) } // type parameters Class MyContainer [T :> SomeBaseClass] { var internal = new List[T] def += (t:T) = internal += t } Values/variables and functions share the same namespace Generics Uses [] instead of () (use () instead of [] as well) Operator overloading
The screwyness of it (2) var greeting = &quot;“ for (i <- 0 until args.length) greeting += (args(i) + &quot; &quot;)  // It’s the same as: val range = 0.until(args.length)  for (i <- range) greeting += (args(i) + &quot; &quot;)  // should use this instead…remember Java // Callback<T>? … ok…now forget it! args.foreach (x => greetings += x) expect (true) {  “ Samba pa ti” == new String (“Samba pa ti”) } . For “for” is not “for” But, “equals” is actually “equals”
Functional…ity Functional language – Lisp family Function literals Lambda stuff and currying It’s fashionable, sounds cool and it’s even useful sometimes… Syntactic sweetness
Functional…ity // a function typedef type Fun =  (String,String) => String // a function literal assigned to a value/variable val aFun =  (x,y) => x+y aFun ( aFun (“this”, “is”), “cool”) // function literal passed to a function: myArray.foreach (  x => println x  ) myArray.sort (<) myArray.sort (  (x,y) => x < y  ) Functions themselves are objects!  You can pass them to other functions, Assign to variables etc … remember C++ pointers to functions) Guess who ^^^ Guess who ^^^
The Cool and the Screwy Abstract VAL implements a DEF  …  or vice-versa Partially applied functions Extend the language syntax Interpreted AND/OR compiled Can setup SCALA-only desktop environment with scripted etc…
Quirks No statics  funny implementation of singletons instead … as “companion objects” Can’t define as many constructors as you want…use factories instead, which is also perfect usage of the singletons above…
Quirks // as a value val abs = if (x < 0) 0–x else x // or as a function – remember? val absfun = (x:int) => if (x < 0) 0–x else x myValue.asInstanceOf [OtherClass] implicit  def itos (x:Int) : String = String.valueOf(x) // check this out: def repeat[T] (n: Int) ( what: => T ): List[T] = ... repeat(5) { println(“I will be quiet in class.&quot;))) }  Every statement block returns a value Typecasts : Implicit type conversions Special syntax: Guess who ^^^ Guess who ^^^
Apply() and bound functions //simple OBJECT to time a statement… note this is not a class !!! apply() behaves differently object Time { def  apply[T]  ( action: => T ): (T, Long) = { startTimer() val resp =  action() val time = stopTimer() (resp, time) } // using it: val (response, ms) =  Time(Http.get(&quot;http://scala-blogs.org/&quot;)) // it works because the http.get(xxx) above is a bound function not an actual call Time(x) is defined via the apply() method Special syntax to bind tuples The Http.get() is NOT a call but a bound function Guess who ^^^ Guess who ^^^
UnitTests class TestRazElement extends JUnit3Suite { def testA = expect (&quot;roota&quot;)  { doc a &quot;name&quot; } def testXpe = expect (&quot;11&quot;) { doc xpe &quot;/root/parent[@name='1']/child[@name='11']&quot; a &quot;name&quot; } } Several ways to write tests. Compatible with JUnit, NGUnit etc Guess who ^^^ Guess who ^^^
Apply() and bound functions //simple OBJECT to time a statement… note this is not a class !!! apply() behaves differently object Time { def  apply[T]  ( action: => T ): (T, Long) = { startTimer() val resp =  action() val time = stopTimer() (resp, time) } // using it: val (response, ms) =  Time(Http.get(&quot;http://scala-blogs.org/&quot;)) // it works because the http.get(xxx) above is a bound function not an actual call Time(x) is defined via the apply() method Special syntax to bind tuples The Http.get() is NOT a call but a bound function Guess who ^^^ Guess who ^^^
String pattern matching // note the triple double quotes “ “ “ val pat = &quot;&quot;&quot;(\w+):(\w+) (.*)&quot;&quot;&quot;.r // bind 3 vals at once val pat(who, cmd, args) =  “john:go someplace” // or just iterate for (s <- pat findAllIn input) println(s) Same patterns as java Special syntax to bind multiple variables at once Guess who ^^^ Guess who ^^^
What Next? Read more (I like what the stuff the links on the next page point to). There’s a lot more to Scala than what I had the time and interest to show here! Start playing with Scala in Eclipse (plugin kinda sucks) or NetBeans (great plugin, especially on a dark background) or vi(m). Have Fun!
Links Good brief Scala intro: http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees   The scala wiki: http:// scala.sygneca.com / Download new verions: http://www.scala-lang.org /   More goodies: http://www.devoxx.com/download/attachments/1705916/D8_U_08_06_01.pdf http://www.slideshare.net/michael.galpin/introduction-to-scala-for-java-developers-presentation http://www.slideshare.net/jboner/pragmatic-real-world-scala-45-min-presentation

Scala - brief intro

  • 1.
    Strengths of ScalaJava replacement? The answer doesn’t matter! Brief intro to Scala - Razvan Cojocaru – Nov’08 & Mar’09
  • 2.
    Overview Brief syntax– at least 30% off Java Smart compiler != dumb programmer Compiles into bytecode, runs on JVM  access to all Java libraries and, more importantly, APIs C++ is back! …mean as ever! Multiple inheritance, operator overloading, true generics, pass functions around, simple syntax Scala is better: true multi-paradigm Functional programming Scalable language Not for the faint of heart!
  • 3.
    Smart Compiler Makesup constructors, getX/setX stuff class Point (x:Int,y:Int) Figures out types for values/variables and functions etc def getX = x Lots of shortcuts in the syntax, i.e no {} for method bodies
  • 4.
    Smart compiler !=dumb programmer Class Point { int x; int y; public Point (int ax, int ay) { this.x = ax; this.y = ay; } public int getX () { return x; } public int getY () { return y; } public int setX (int x) { if (x <= 0) throw new IllegalArgumentException(“blah”); else this.x=x } public int setY (int y) { this.y=y } } Class Point ( var x:int, var y:int) def x_= (ax:Int) = require (ax > 0); x=ax To overwrite the assign, is actually a little more complicated: def + (p:Point) = new Point (x+p.x, y+p.y) Guess who ^^^ Guess who ^^^
  • 5.
    Constructor/field generation class SimplerPoint ( private var ix : Int, private var iy :Int) { def x = ix def y = iy def x_= ( ax :Int) { require( ax >0); ix = ax } def y_= ( ay :Int) { require( ay >0); iy = ay } } class Point (ax:Int, ay:Int) { private[this] var ix :Int = ax private[this] var iy :Int = ay def x = ix def y = iy def x_= (ax:Int) { require(ax>0); ix =ax } def y_= (ay:Int) { require(ay>0); iy =ay } } // check this out !!! class Point (ax:Int, ay:Int) { require(ax>0); // class body is in fact c-tor private[this] var ix :Int = ax def x_= (ax:Int) { require(ax>0); ix =ax } } Ix/iy are both constructor and fields Classic: ax/ay are just args for constructor
  • 6.
    Traits Like multipleinheritance More like “polymorphic composition”…if that pairing makes sense  Simplify coding a lot, for classes with multiple “traits”. No interfaces There are abstract classes, though An abstract trait (all methods abstract) is equivalent to a Java interface
  • 7.
    Traits - featuresAs opposed to interfaces, traits can implement methods No “controllers” etc No replication of code. With single inheritance, you decide on a base class and then REWRITE every time the methods of other implemented interfaces “ idiot controller” syndrome: keep algorthms in different classes, to avoid rewriting them, see next slide TODO: read about the “linearization” to avoid diamond inheritance Same as “mixin” in Ruby Trait vs. Class ? Semantics …
  • 8.
    Traits vs interfacesinterface Centered { public Point getCenter () { return x; } } class IdiotController { public void offset (Centered s, Point offsetBy) {…} } class MyShape extends Drawable implements Centered { //… public Point getCenter () { return c; } } //…in a java file far far away: New IdiotController().offset (myShape, new Point (3,4)) trait Centered () { var center:Point def offset (offsetBy:Point) = center += offsetBy } Class MyShape extends Drawable with Centered { } //…in a scala file anywereh in the galaxy myShape.offset ((3,4)) Guess who ^^^ Guess who ^^^
  • 9.
    The screwyness ofit trait AnotherCentered { def center:Point def offset (offsetBy:Point) = center += offsetBy } class AnotherShape extends AnotherCentered { override val center:Point = new Point(0,0) } // type parameters Class MyContainer [T :> SomeBaseClass] { var internal = new List[T] def += (t:T) = internal += t } Values/variables and functions share the same namespace Generics Uses [] instead of () (use () instead of [] as well) Operator overloading
  • 10.
    The screwyness ofit (2) var greeting = &quot;“ for (i <- 0 until args.length) greeting += (args(i) + &quot; &quot;) // It’s the same as: val range = 0.until(args.length) for (i <- range) greeting += (args(i) + &quot; &quot;) // should use this instead…remember Java // Callback<T>? … ok…now forget it! args.foreach (x => greetings += x) expect (true) { “ Samba pa ti” == new String (“Samba pa ti”) } . For “for” is not “for” But, “equals” is actually “equals”
  • 11.
    Functional…ity Functional language– Lisp family Function literals Lambda stuff and currying It’s fashionable, sounds cool and it’s even useful sometimes… Syntactic sweetness
  • 12.
    Functional…ity // afunction typedef type Fun = (String,String) => String // a function literal assigned to a value/variable val aFun = (x,y) => x+y aFun ( aFun (“this”, “is”), “cool”) // function literal passed to a function: myArray.foreach ( x => println x ) myArray.sort (<) myArray.sort ( (x,y) => x < y ) Functions themselves are objects! You can pass them to other functions, Assign to variables etc … remember C++ pointers to functions) Guess who ^^^ Guess who ^^^
  • 13.
    The Cool andthe Screwy Abstract VAL implements a DEF … or vice-versa Partially applied functions Extend the language syntax Interpreted AND/OR compiled Can setup SCALA-only desktop environment with scripted etc…
  • 14.
    Quirks No statics funny implementation of singletons instead … as “companion objects” Can’t define as many constructors as you want…use factories instead, which is also perfect usage of the singletons above…
  • 15.
    Quirks // asa value val abs = if (x < 0) 0–x else x // or as a function – remember? val absfun = (x:int) => if (x < 0) 0–x else x myValue.asInstanceOf [OtherClass] implicit def itos (x:Int) : String = String.valueOf(x) // check this out: def repeat[T] (n: Int) ( what: => T ): List[T] = ... repeat(5) { println(“I will be quiet in class.&quot;))) } Every statement block returns a value Typecasts : Implicit type conversions Special syntax: Guess who ^^^ Guess who ^^^
  • 16.
    Apply() and boundfunctions //simple OBJECT to time a statement… note this is not a class !!! apply() behaves differently object Time { def apply[T] ( action: => T ): (T, Long) = { startTimer() val resp = action() val time = stopTimer() (resp, time) } // using it: val (response, ms) = Time(Http.get(&quot;http://scala-blogs.org/&quot;)) // it works because the http.get(xxx) above is a bound function not an actual call Time(x) is defined via the apply() method Special syntax to bind tuples The Http.get() is NOT a call but a bound function Guess who ^^^ Guess who ^^^
  • 17.
    UnitTests class TestRazElementextends JUnit3Suite { def testA = expect (&quot;roota&quot;) { doc a &quot;name&quot; } def testXpe = expect (&quot;11&quot;) { doc xpe &quot;/root/parent[@name='1']/child[@name='11']&quot; a &quot;name&quot; } } Several ways to write tests. Compatible with JUnit, NGUnit etc Guess who ^^^ Guess who ^^^
  • 18.
    Apply() and boundfunctions //simple OBJECT to time a statement… note this is not a class !!! apply() behaves differently object Time { def apply[T] ( action: => T ): (T, Long) = { startTimer() val resp = action() val time = stopTimer() (resp, time) } // using it: val (response, ms) = Time(Http.get(&quot;http://scala-blogs.org/&quot;)) // it works because the http.get(xxx) above is a bound function not an actual call Time(x) is defined via the apply() method Special syntax to bind tuples The Http.get() is NOT a call but a bound function Guess who ^^^ Guess who ^^^
  • 19.
    String pattern matching// note the triple double quotes “ “ “ val pat = &quot;&quot;&quot;(\w+):(\w+) (.*)&quot;&quot;&quot;.r // bind 3 vals at once val pat(who, cmd, args) = “john:go someplace” // or just iterate for (s <- pat findAllIn input) println(s) Same patterns as java Special syntax to bind multiple variables at once Guess who ^^^ Guess who ^^^
  • 20.
    What Next? Readmore (I like what the stuff the links on the next page point to). There’s a lot more to Scala than what I had the time and interest to show here! Start playing with Scala in Eclipse (plugin kinda sucks) or NetBeans (great plugin, especially on a dark background) or vi(m). Have Fun!
  • 21.
    Links Good briefScala intro: http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees The scala wiki: http:// scala.sygneca.com / Download new verions: http://www.scala-lang.org / More goodies: http://www.devoxx.com/download/attachments/1705916/D8_U_08_06_01.pdf http://www.slideshare.net/michael.galpin/introduction-to-scala-for-java-developers-presentation http://www.slideshare.net/jboner/pragmatic-real-world-scala-45-min-presentation