Download Scala

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Scala
or
”The Free Lunch is Over”
Andreas Enbohm
Capgemini Sverige AB
Why Scala

The free lunch is over...

Today – 2 Cores

2010 maybe 12 (AMD), in 5 years maybe 16

Difficult to utilize several CPUs with Java

Huge API in current Java – some argue it may collape due to its own weight

Scala = ScalableLanguage

Designed to fit todays and some of tomorrows programming paradigms

Actors – Easier to utilize than memory synchronization (more about this later)

Nice (less boiler plate code) syntax and ’type safe duck typing’

And much more...
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Scala - Features

OO and functional language
”a general purpose programming language designed to express common programming patterns in a concise,
elegant, and type-safe way”

Functional language – (often) no side effect, avoids state and mutable data, i.e functions can run independently and
without knowlegde of eachother
def sum(a:Int,b:Int) = a+b

Open Source

Compact code, ca 50 % less code than Java

Static typed language (but with ’kind of’ duck typing, more about this later)

Pattern matching, singel inheritance, immutable collections (like Java Strings), XML as FCC

SUnit, Lift (web framework), Support for Maven, Ant, Plugins for Eclipse, Netbeans, IntelliJ

Why not Ruby, Groovy, F#?
- Fully interoperable with Java (call Java classes whenever you want)
- Refactoring (static typed)
- runs on world’s best VM!
- very simple to inherit from Java classes
- Javas annotations, threads, for each, it all works
- Very fast (600x faster than groovy, lift 6x faster than Rails?)
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Scala – Compared to Java

Defining a class
public class Person
{
private String firstName;
private String lastName;
class Person(var firstName: String, var lastName: String) {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}

Everything in Scala is an Object! This also includes functions
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Scala – Compared to Java

Defining variables - ; and type can often be omitted
val myInt: Int = 1;
val anotherInt = 2

Creating objects
val anObject = Object //Omit () if you want just ’cluttering’ your code
val aList = List(”John Doe”, ”Jane Doe”, ”Baby Doe”)

List is of type List[String] by default
List<String> aList = new ArrayList<String>(); //Java syntax for creating a list-object
val aList = List //Scala syntax for creating corresponding list
val aList = List[String]

//Also works, notice just ONE generic definiton
List objects in Scala contains several useful functions to access elements in the List
println("Hi, " +aList.tail.head) //Prints “Hi, Jane Doe”

Ommiting some dots…
import java.util.{Date,Locale}
import java.text.DateFormat
import java.text.DateFormat._
val now = new Date
val df = getDateInstance(LONG, Locale.FRANCE)
println( df format now) //same as df.format(now)
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Scala – Compared to Java

Exceptions
- Scala has no checked exception (unlike Java but like C#)
- If used with Java, use annotation @throws(classOf[IOException])
try { doSomething(params) }
catch {
case ex: IOException => println("Oops! Some file is probably missing")
case ex: NullPointerException => println(“Dohh!! Must initialize the variable ")
}

Using pattern matching and functions
object MatchTest1 extends Application {
def matchTest(x: Int): String =
x match {
case 1 => "one"
case 2 => "two"
case _ => "many"
}
println(matchTest(1)) //Prints “one”
println(matchTest(99)) //Prints “many”
}

Scala uses ’traits’ which can be compared to interfaces. Can have implementations (but no state)
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Duck Typing in Scala

”If it walks like a duck and quacks like a duck, then I would call it a duck.” – Wise Guy
class Duck {
public void quack() {
print(”Duck Quacking!”)
}
class Person {
public void quack() {
print(”Person Quacking!”)
}
}
Duck d = new Duck();
Person p = new Person();
testQuack(d);
testQucak(p);
testQuack(duckableObject) {
duckableObject.quack();
//Lets hope this work!!!
}

Statically typed language don’t offer this flexibility (Java, C#)
- i.e. no ’Duck Typing’

Downside – what happens if object does not have a ’quack’-method -> RuntimeException!

In Java, we must add an interface with method ’quack()’ – impossible to add an interface without changing the class!
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Duck Typing in Scala

However Scala offers ’Structual Typing’ – a.k.a. Type safe duck typing

Consider following example (Scala syntax)
class File(name: String) {
def getName(): String = name
def open() { /*..*/ }
def close() { println("close file") }
}
def testPrintName(aFileObject: { def getName(): String }) {
println(aFileObject.getName)
}
testPrintName(new File("test.txt"))
testPrintName(new java.io.File("test.txt"))

Scala offers structual typing, i.e. def getName() in test

The structual type ’getName()’ checks at compile time that ’aFileObject’ has a getName() method if not – compile
error

If getName() is needed more than one, use traits.
trait HasName {
def getName() : String
}
def testPrintName(HasName f) = { println(f.getName) }
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Actors

”Don't bring the grape juice into the living room“ – Brian Goetz

Java threads
- shared memory, i.e. only one thread can operate on a shared resource concurrently
- expensive to create, i.e. every thread has a high memory consumption
- context switch. i.e a Java thread maps to a OS thread (limited numbers ~3K)
- context switch make page faults - > slow due to thread needs to re-read data from RAM
- difficult to use, i.e. deadlocks, raise conditions, live locks, NASA Mars explorer experied live lock
- synchronize, i.e. not just a a monitor/lock but also write to main memory (no registers) ~100 slower!
- Java was designed for single processors, not multi-cores!

Actor based concurrency
- concurrenct processes communicates by exchanging messages
- asynchronous message passing
- ’share-nothing’-model
- Erlang early to implement this style of concurrency
- Erlang based web server ~80000 clients, Apache ~4000 clients

Two flavours in Scala;
- Thread based actors – high level abstraction of threads which replaces error-prone shared memory access
- Thread less actors – offers enourmous scalability. Lightweight processes are used as actors with much less overhead than a usual thread.
’Piggy-backs’ on calling threads stack trace (continuation closure)
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Downsides

”With great power comes great complexity” – James Gosling

New languages difficult to introduce to organisations

Not ready for prime time?
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm
Questions?
http://www.scala-lang.org/
© 2004 Capgemini - All rights reserved
2008, July – Andreas Enbohm