Scala - brief intro

21
Strengths of Scala Java replacement? The answer doesn’t matter! Brief intro to Scala - Razvan Cojocaru – Nov’08 & Mar’09

description

simple intro to scala for java folks

Transcript of Scala - brief intro

Page 1: Scala - brief intro

Strengths of Scala

Java replacement?

The answer doesn’t matter!

Brief intro to Scala - Razvan Cojocaru – Nov’08 & Mar’09

Page 2: Scala - brief intro

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!

Page 3: Scala - brief intro

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

Page 4: Scala - brief intro

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 ^^^

Page 5: Scala - brief intro

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

Page 6: Scala - brief intro

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

Page 7: Scala - brief intro

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…

Page 8: Scala - brief intro

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 galaxymyShape.offset ((3,4))

Guess who ^^^Guess who ^^^

Page 9: Scala - brief intro

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

Page 10: Scala - brief intro

The screwyness of it (2)

var greeting = "“for (i <- 0 until args.length)

greeting += (args(i) + " ")

// It’s the same as:

val range = 0.until(args.length) for (i <- range)

greeting += (args(i) + " ")

// 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”

Page 11: Scala - brief intro

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

Page 12: Scala - brief intro

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 )

Guess who ^^^Guess who ^^^

Functions themselves are objects!

You can pass them to other functions,

Assign to variables etc

…remember C++ pointers to functions)

Page 13: Scala - brief intro

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…

Page 14: Scala - brief intro

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…

Page 15: Scala - brief intro

Quirks

// as a valueval 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.")))}

Guess who ^^^Guess who ^^^

Every statement block returns a value

Typecasts :

Implicit type conversions

Special syntax:

Page 16: Scala - brief intro

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("http://scala-blogs.org/"))

// it works because the http.get(xxx) above is a bound function not an actual call

Guess who ^^^Guess who ^^^

Time(x) is defined via the apply() method

Special syntax to bind tuples

The Http.get() is NOT a call but a bound function

Page 17: Scala - brief intro

UnitTests

class TestRazElement extends JUnit3Suite {

def testA =

expect ("roota") { doc a "name" }

def testXpe =

expect ("11") { doc xpe "/root/parent[@name='1']/child[@name='11']" a "name" }

}

Guess who ^^^Guess who ^^^

Several ways to write tests. Compatible with JUnit, NGUnit etc

Page 18: Scala - brief intro

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("http://scala-blogs.org/"))

// it works because the http.get(xxx) above is a bound function not an actual call

Guess who ^^^Guess who ^^^

Time(x) is defined via the apply() method

Special syntax to bind tuples

The Http.get() is NOT a call but a bound function

Page 19: Scala - brief intro

String pattern matching

// note the triple double quotes “ “ “ val pat = """(\w+):(\w+) (.*)""".r // bind 3 vals at once val pat(who, cmd, args) =

“john:go someplace” // or just iterate for (s <- pat findAllIn input) println(s)

Guess who ^^^Guess who ^^^

Same patterns as java

Special syntax to bind multiple variables at once

Page 20: Scala - brief intro

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!

Page 21: Scala - brief intro

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