Scala introduction

Post on 15-Jan-2015

1.027 views 3 download

Tags:

description

for Sayeret Lambda January 2011 meeting

Transcript of Scala introduction

Introductionhttp://www.scala-lang.org

Sayeret LambdaJanuary 2011

Yardena Meymann

What is Scala

• Object oriented and functional• Statically typed - advanced type system• Compiled to JVM bytecode

but also to CLR, and to JavaScript (in progress)• High performance• Very good interoperability with Java• Support for modularity and extensibility

DSL friendly

History

1995Sun and Netscape team up

and announce first beta release of Java

History

1995Philip Wadler tells Martin

Odersky about Java.

Odersky decides to learn the language by writing a compiler

History

1999Sun buys Java compiler from Martin

Odersky, it is shipped with JDK 1.3

OUR JAVA COMPILER ISN’T GOOD ENOUGH

I KNOW THIS GUY IN SWITZERLAND, HE WROTE A GREAT JAVA COMPILER !

History

1999Work on adding generics to Java begins

History

2001Martin Odersky starts working on Scala at

Then and Now

2003 Scala 1.02006 Scala 2.02010 Scala 2.8

“If I were to pick a language to use today other than Java, it would be Scala”

James Gosling

Now

• Open source projects in Scala: – Akka, Lift, Specs, ScalaCheck, Scalaz, ScalaQuery, …

• Books:

• Tools: – built-in REPL, Eclipse, IntelliJ and NetBeans plug-ins– integration modules for almost every popular Java

framework

Now

• Used in industry: – LinkedIn, Twitter, Novell, EDF, The Guardian,

Xebia, Xerox, Sony, Siemens, …

• Jobs:

Influences on Scala Design• Java, C# – syntax, basic types, and class libraries,

• Smalltalk – uniform object model,

• Eiffel – uniform access principle,

• Beta – systematic nesting,

• ML, Haskell – many of the functional aspects.

Imagine

No Primitives

Everything is an object

No Operators (almost)

Everything is a method

1 + 21.+(2)

123 toString123.toString()

No Noise

• Semicolon inference• Type inference• Empty and single line blocks don’t need { }• Infix notation for method invocations• Implicit public• Empty parameter lists don’t need ()

No Statements

Everything is an expression• Return is optional, last expression is returned

def plus2(x:Int) = x + 2

• for, while, if/else are expressions• Unit equivalent of void

No final

• val and var, memoization

def foo() { val x = “immutable” var y = “mutable” lazy val z = “lazy”}

No Checked Exceptions

All exceptions are runtime

Also, you have Option[T] and Either[A,B] that can be used instead of checked exceptions

No Statics

And no “manual” singletonsInstead we have object – companion class

object HelloWorld {def main(args: Array[String]) =

println("Hello, world!")}

First-class Functions

val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V")

An object with apply method can be used as a function

val inc = (x: Int) => x + 1

inc(1) 2

No “Java Bean” BoilerplateJava

public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(age: int) { this.age = age; }}

Scalaclass Person( var name: String, var age: Int)

Case Classes

Also generates equals, hashCode and allows decomposition via pattern matching

abstract class Term case class Var(name: String) extends Term case class Fun(arg: String, body: Term) extends Term case class App(f: Term, v: Term) extends Term

No Switch – Pattern Matching

Extractor objects are auto-generated for case classesdef printTerm(term: Term) { term match { case Var(n) => print(n) case Fun(x, b) => print("^" + x + ".") ; printTerm(b) case App(f, v) => Console.print("(");printTerm(f); print(" "); printTerm(v); print(")") } }

def isIdentityFun(term: Term): Boolean = term match { case Fun(x, Var(y)) if x == y => true case _ => false }

Functions and Closures

List(1, 2, 3).map((x: Int) => x + 1) List(2, 3, 4)

List(1, 2, 3).map(x => x + 1)

List(1, 2, 3).map(_ + 1)

With some syntax sugar:

Closures:

var more = 7val addMore = (x: Int) => x + more 10

Lists

val list = 1 :: 2 :: 3 :: Nillist.head 1list.tail List(2, 3)list.map(_ + 1) List(2, 3, 4)list.filter(_ < 2) List(3)list.exists(_ == 3) truelist.drop(2) List(3)list.reverse List(3, 2, 1)list.sort(_ > _) List(3, 2, 1)List.flatten(list) List(1, 2, 3)list.slice(2, 3) List(3)...

Tuples

def getNameAndAge: Tuple2[String, Int] = {val name = ...val age = ...(name, age)

}val (name, age) = getNameAndAgeprintln(“Name: “ + name)println(“Age: “ + age)

For Comprehensions

Find all attendees named Fred that speaks Danish

for {att <- attendeesif att.name == “Fred”lang <- att.spokenLanguagesif lang == “Danish”

} yield att

No Interfaces

Traits for mixin composition trait Dad { private var children: List[Child] = Nil def addChild(child: Child) = children = child :: children def getChildren = children.clone}

class Man(val name: String) extends Human

val jonas = new Man(“Jonas”) with Dadjonas.addChild(new Child(“Jacob”))

class Man(val name: String) extends Human with Dad

Traits for Multiple Inheritance

val order = new Order(customer)with Entitywith InventoryItemSetwith Invoicablewith PurchaseLimiterwith MailNotifierwith ACLwith Versionedwith Transactional

Traits – Stackable Modificationtrait IgnoreCaseSet extends java.util.Set[String] { abstract override def add(e: String) = {

super.add(e.toLowerCase) } abstract override def contains(e: String) = {

super.contains(e.toLowerCase) } abstract override def remove(e: String) = {

super.remove(e.toLowerCase) }}

Many More…

• Far more powerful generics• Self types• High-order types• Structural and dependent types• Declaration-site variance and existential types

support• Views (implicit conversions) and implicit

arguments

Many More…

• Currying, partial functions• Continuations• Built-in XML support• …

This presentation is based on

Pragmatic Real-World Scalaby Jonas Bonérhttp://www.slideshare.net/jboner/pragmatic-real-world-scala-45-min-presentation