SlideShare a Scribd company logo
Andreas Enbohm 2009-03-15 Scala or ” The Free Lunch is Over”
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...
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 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?)  def  sum(a:Int,b:Int) = a+b
Scala – Compared to Java Defining a class Everything in Scala is an Object! This also includes functions class  Person (var firstName: String, var lastName: String) {  } public   class  Person { private  String firstName; private  String lastName; 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; } }
Scala – Compared to Java Defining variables - ; and type can often be omitted Creating objects List is of type List[String] by default List objects in Scala contains several useful functions to access elements in the List Ommiting some dots… val  myInt: Int = 1;  val  anotherInt = 2  val  anObject = Object //Omit () if you want just ’cluttering’ your code val  aList = List(”John Doe”, ”Jane Doe”, ”Baby Doe”) println (&quot;Hi, &quot; +aList.tail.head) //Prints “Hi, Jane Doe”  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 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)
Scala – Compared to Java Exceptions - Scala has no checked exception (unlike Java but like C#) - If used with Java, use annotation @throws(classOf[IOException]) Using pattern matching and functions Scala uses ’ traits’  which can be compared to interfaces. Can have implementations (but no state) try  { doSomething(params) }  catch  {  case ex: IOException => println(&quot;Oops! Some file is probably missing&quot;)  case ex: NullPointerException => println(“Dohh!! Must initialize the variable &quot;)  }  object  MatchTest1 extends  Application  {  def  matchTest(x: Int): String =  x match {  case 1 => &quot;one&quot;  case 2 => &quot;two&quot;  case _ => &quot;many&quot;  } println (matchTest(1)) //Prints “one”   println (matchTest(99)) //Prints “many” }
Duck Typing in Scala ” If it walks like a duck and quacks like a duck, then I would call it a duck.” – Wise Guy 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! 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!!!   }
Duck Typing in Scala However Scala offers ’Structual Typing’ – a.k.a. Type safe duck typing Consider following example (Scala syntax) 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. class  File (name: String) {  def getName(): String = name  def open() { /*..*/ }  def close() { println(&quot;close file&quot;) }  }  def  testPrintName (aFileObject: { def getName(): String }) {  println (aFileObject.getName)  }  testPrintName (new File(&quot;test.txt&quot;))  testPrintName (new java.io.File(&quot;test.txt&quot;))  trait  HasName {  def getName() : String  }  def  testPrintName (HasName f) = { println(f.getName) }
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)
Downsides ” With great power comes great complexity” – James Gosling New languages difficult to introduce to organisations Not ready for prime time?
Questions? http://www.scala-lang.org/

More Related Content

PPTX
Java7 - Top 10 Features
PPTX
Hybrid Applications
PPTX
What's new in Java 11
PPTX
Java 7 Whats New(), Whats Next() from Oredev
PPT
55 New Features in Java 7
KEY
JavaOne 2011 - JVM Bytecode for Dummies
PDF
JavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor Buzatović
ODP
Open Source Compiler Construction for the JVM
Java7 - Top 10 Features
Hybrid Applications
What's new in Java 11
Java 7 Whats New(), Whats Next() from Oredev
55 New Features in Java 7
JavaOne 2011 - JVM Bytecode for Dummies
JavaCro'14 - Is there Kotlin after Java 8 – Ivan Turčinović and Igor Buzatović
Open Source Compiler Construction for the JVM

What's hot (19)

PDF
Connecting the Worlds of Java and Ruby with JRuby
PDF
Kotlin - Better Java
PDF
Using Java from Ruby with JRuby IRB
PDF
Seeking Clojure
PPTX
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
PPTX
Mastering Java Bytecode - JAX.de 2012
PPTX
Software Uni Conf October 2014
PDF
Camel and JBoss
PPTX
K is for Kotlin
PPTX
JRuby in Java Projects
PPTX
SoftwareUniversity seminar fast REST Api with Spring
PDF
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
PDF
Faster & Greater Messaging System HornetQ zzz
PDF
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
PDF
TorqueBox - Ultrapassando a fronteira entre Java e Ruby
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PPT
Java New Evolution
PPT
Java, Ruby & Rails
PPT
Invoke dynamics
Connecting the Worlds of Java and Ruby with JRuby
Kotlin - Better Java
Using Java from Ruby with JRuby IRB
Seeking Clojure
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Mastering Java Bytecode - JAX.de 2012
Software Uni Conf October 2014
Camel and JBoss
K is for Kotlin
JRuby in Java Projects
SoftwareUniversity seminar fast REST Api with Spring
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Faster & Greater Messaging System HornetQ zzz
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing
TorqueBox - Ultrapassando a fronteira entre Java e Ruby
Productive Programming in Java 8 - with Lambdas and Streams
Java New Evolution
Java, Ruby & Rails
Invoke dynamics
Ad

Viewers also liked (6)

PPTX
Behavior-driven Development and Lambdaj
PPT
Project Lambda - Closures after all?
PPTX
Java Extension Methods
PPTX
Software Craftsmanship
PPTX
BDD Short Introduction
PPT
SOLID Design Principles
Behavior-driven Development and Lambdaj
Project Lambda - Closures after all?
Java Extension Methods
Software Craftsmanship
BDD Short Introduction
SOLID Design Principles
Ad

Similar to Scala (20)

ODP
A Tour Of Scala
PPT
scala-intro
PPT
Scala presentationjune112011
PDF
Scala and jvm_languages_praveen_technologist
PPTX
Scala-Ls1
PPT
Scala Talk at FOSDEM 2009
PPT
Why scala - executive overview
PDF
Stepping Up : A Brief Intro to Scala
PPTX
All about scala
PPTX
Scala in practice
PPTX
Scala adoption by enterprises
PDF
A Brief, but Dense, Intro to Scala
PDF
Scala a case4
PDF
Scala Sjug 09
PDF
Miles Sabin Introduction To Scala For Java Developers
PDF
A Brief Introduction to Scala for Java Developers
PDF
Scala - from "Hello, World" to "Heroku Scale"
PDF
Yes scala can!
PDF
Lecture1
PPTX
Scala, Play 2.0 & Cloud Foundry
A Tour Of Scala
scala-intro
Scala presentationjune112011
Scala and jvm_languages_praveen_technologist
Scala-Ls1
Scala Talk at FOSDEM 2009
Why scala - executive overview
Stepping Up : A Brief Intro to Scala
All about scala
Scala in practice
Scala adoption by enterprises
A Brief, but Dense, Intro to Scala
Scala a case4
Scala Sjug 09
Miles Sabin Introduction To Scala For Java Developers
A Brief Introduction to Scala for Java Developers
Scala - from "Hello, World" to "Heroku Scale"
Yes scala can!
Lecture1
Scala, Play 2.0 & Cloud Foundry

Scala

  • 1. Andreas Enbohm 2009-03-15 Scala or ” The Free Lunch is Over”
  • 2. 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...
  • 3. 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 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?) def sum(a:Int,b:Int) = a+b
  • 4. Scala – Compared to Java Defining a class Everything in Scala is an Object! This also includes functions class Person (var firstName: String, var lastName: String) { } public class Person { private String firstName; private String lastName; 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; } }
  • 5. Scala – Compared to Java Defining variables - ; and type can often be omitted Creating objects List is of type List[String] by default List objects in Scala contains several useful functions to access elements in the List Ommiting some dots… val myInt: Int = 1; val anotherInt = 2 val anObject = Object //Omit () if you want just ’cluttering’ your code val aList = List(”John Doe”, ”Jane Doe”, ”Baby Doe”) println (&quot;Hi, &quot; +aList.tail.head) //Prints “Hi, Jane Doe” 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 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)
  • 6. Scala – Compared to Java Exceptions - Scala has no checked exception (unlike Java but like C#) - If used with Java, use annotation @throws(classOf[IOException]) Using pattern matching and functions Scala uses ’ traits’ which can be compared to interfaces. Can have implementations (but no state) try { doSomething(params) } catch { case ex: IOException => println(&quot;Oops! Some file is probably missing&quot;) case ex: NullPointerException => println(“Dohh!! Must initialize the variable &quot;) } object MatchTest1 extends Application { def matchTest(x: Int): String = x match { case 1 => &quot;one&quot; case 2 => &quot;two&quot; case _ => &quot;many&quot; } println (matchTest(1)) //Prints “one” println (matchTest(99)) //Prints “many” }
  • 7. Duck Typing in Scala ” If it walks like a duck and quacks like a duck, then I would call it a duck.” – Wise Guy 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! 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!!! }
  • 8. Duck Typing in Scala However Scala offers ’Structual Typing’ – a.k.a. Type safe duck typing Consider following example (Scala syntax) 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. class File (name: String) { def getName(): String = name def open() { /*..*/ } def close() { println(&quot;close file&quot;) } } def testPrintName (aFileObject: { def getName(): String }) { println (aFileObject.getName) } testPrintName (new File(&quot;test.txt&quot;)) testPrintName (new java.io.File(&quot;test.txt&quot;)) trait HasName { def getName() : String } def testPrintName (HasName f) = { println(f.getName) }
  • 9. 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)
  • 10. Downsides ” With great power comes great complexity” – James Gosling New languages difficult to introduce to organisations Not ready for prime time?

Editor's Notes

  • #3: Processorerna blir inte snabbare snarare tvärom. Dock gäller Moores lag fortfarande (2x transistorer på 18 mån). Problem med klockfrekvens Amhdals lag - &gt; hur mycket snabbare blir applikationen när du tillför nya resursen (processorer etc). En app kan inte bli snabbare än sin minst paralelliserbara del.
  • #7: Functins are defined with ’def’
  • #8: Har visat sig att statisk kompilerade språk inte ger den fördel man trott - &gt; inte så många rte som ske dock mycket bra med dynamisk typade språk
  • #10: 20 testers per programmer ~1 200 0000 Other types of concurrency, transaction based memory, quasi-static scheduling, AOP How many of you can write thread safe code