introduction to scala

53
SCALA Java Klassentreffen 2013 Manuel Bernhardt

Upload: manuel-bernhardt

Post on 10-May-2015

2.796 views

Category:

Technology


1 download

DESCRIPTION

Introduction to the Scala programming language @ the Java Klassentreffen 2013 in Vienna and Linz organized by http://www.javaklassentreffen.at Introducing the background, design goals, and some examples (from a Java perspective) http://java.at/web/guest/jkt13

TRANSCRIPT

Page 1: Introduction to Scala

SCALAJava Klassentreffen 2013

Manuel Bernhardt

Page 2: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

•Why Scala?

• Scala in the wild

• The Code / Scala in practice

• Tools & more

Page 3: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

YOUR SPEAKER

• Independent software consultant

•Web, web, web

• Java & Scala & Javascript

•Open-Source

•Delving

Page 4: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

•Why Scala?

• Scala in the wild

• The Code / Scala in practice

• Tools & more

Page 5: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

HISTORY

•Martin Odersky, EPFL

• Espresso, Pizza, GJ, Javac

• Funnel, Scala

• First Scala release in 2003

Page 6: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

• Why Scala?

• Scala in the wild

• The Code / Scala in practice

Page 7: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

Page 8: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

• Full interoperability with Java

Page 9: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

• Full interoperability with Java

• Cut down boilerplate

Page 10: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

• Full interoperability with Java

• Cut down boilerplate

• Pure object orientation & functional programming

Page 11: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

• Full interoperability with Java

• Cut down boilerplate

• Pure object orientation & functional programming

•Move away from null

Page 12: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA DESIGN GOALS

• Full interoperability with Java

• Cut down boilerplate

• Pure object orientation & functional programming

•Move away from null

•Multi-core programming

Page 13: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

•Why Scala?

• Scala in the wild

• The Code / Scala in practice

• Tools & more

Page 14: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

WHAT PEOPLE SAY

If I were to pick a language todayother than Java, it would be Scala.

James GoslingFather of Java

Page 15: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

WHAT PEOPLE SAY

I can honestly say if someone had shown me the Programming Scala book by Martin Odersky, Lex Spoon

& Bill Venners back in 2003 I’d probably have never created Groovy.

James StrachanCreator of Groovy

Page 16: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

ThoughtWorks TechRadar May 2013http://www.thoughtworks.com/radar

Page 17: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA IN THE WILD

Page 18: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA IN THE WILD

etc.

Page 19: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA IN VIENNA

• openForce - http://openforce.com

• x-tradesoft - http://xtradesoft.com

•Delving - http://www.delving.eu

• dimocom - http://www.dimocom.com

• emarsys - http://www.emarsys.com

•Miavia - https://miavia.in

Page 20: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SCALA IN VIENNA

• Scala Vienna User Group

• http://scala-vienna.org/

Next meeting: 26th September 6 PM - Sektor 5

Page 21: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

•Why Scala?

• Scala in the wild

• The Code / Scala in practice

• Tools & more

Page 22: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AVOIDING THE BILLION-DOLLAR MISTAKE

But I couldn't resist the temptation to put in a null

reference, simply because it was so easy to implement

Tony Hoare Creator of ALGOL

Page 23: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AVOIDING THE BILLION- DOLLAR MISTAKE

val maybeUser: Option[User] = User.findOneByName("bob")// returns Some[User]

maybeUser == None // false

maybeUser.foreach { user => println(user.fullName) // prints "Bob Marley" if there is a user!}

val name = maybeUser.map(_.name).getOrElse("Unknown user")

Page 24: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

CONCISENESSpublic class User {

! private String name;

! private String surname;

! private String email;

! public User(String name, String surname, String email) {! ! this.name = name;! ! this.surname = surname;! ! this.email = email;! }

! public void setName(String name) {! ! this.name = name;! }

! public void setSurname(String surname) {! ! this.surname = surname;! }

! public void setEmail(String email) {! ! this.email = email! }

! public String getName() {! ! return this.name;! }

! public String getSurname() {! ! return this.surname;! }

! public String getEmail() {! ! return this.surname;! }

}

Page 25: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

CONCISENESSclass User( var name: String, var surname: String, var email: String)

val bob = new User("Bob", "Marley", "[email protected]")// bob: User = User@5c3f1224

bob.name // res0: String = Bob

bob.name = "Bobby" // bob.name: String = Bobby

Page 26: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

CONCISENESSpublic class ImmutableUser {

! private final String name;

! private final String surname;

! private final String email;

! public ImmutableUser(String name, String surname, String email) {! ! this.name = name;! ! this.surname = surname;! ! this.email = email;! }

! public String getName() {! ! return this.name;! }

! public String getSurname() {! ! return this.surname;! }

! public String getEmail() {! ! return this.surname;! }

! @Override public int hashCode() {

! ! // yada yada yada! }

! @Override public boolean equals(Object that) {

! ! // yada yada yada

! }

}

Page 27: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

CONCISENESScase class ImmutableUser( name: String, surname: String, email: String)

val bob = ImmutableUser("Bob", "Marley", "[email protected]")// hashcode and equals for free!

val namedBob = ImmutableUser(name = "Bob", surname = "Marley", email = "email")

val bobby = bob.copy(name = "Bobby") // returns a User with name Bobby

bob.toString // res0: String = ImmutableUser(Bob,Marley,email)

Page 28: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

USEFUL TYPE INFERENCE

val foo = "Bar" // foo: String = Bar

val answer = 42 // answer: Int = 42

val price = 9.99 // price: Double = 9.99

val nums = List(1, 2, 3) // nums: List[Int] = List(1, 2, 3)

val map = Map("abc" -> List(1, 2, 3))// map: scala.collection.immutable.Map[String,List[Int]] = Map(abc -> List(1, 2, 3))

Page 29: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

EXPLICIT TYPING

val foo: String = "Bar" // foo: String = Bar

val answer: Int = 42 // answer: Int = 42

val price: Double = 9.99 // price: Double = 9.99

val nums: List[Int] = List(1, 2, 3) // nums: List[Int] = List(1, 2, 3)

val map: Map[String, List[Int]] = Map("abc" -> List(1, 2, 3))// map: scala.collection.immutable.Map[String,List[Int]] = Map(abc -> List(1, 2, 3))

Page 30: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

users.sort(new Comparator { public int compare(Object user1, Object user2) { ! int userAge1 = ((User) user1).getAge(); ! int userAge2 = ((User) user2).getAge(); ! if (userAge1 > userAge2) { ! ! return 1; ! } else if userAge1 < userAge2) {! ! ! return -1;! ! } else {! ! ! return 0;! ! }

! }});

Page 31: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

def sortByAge(user1: User, user2: User) = user1.age > user2.age

users.sortWith(sortByAge)

Page 32: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

users.sortWith((user1, user2) => user1.age > user2.age)

Page 33: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

users.sortWith(_.age > _.age)

Page 34: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

List<User> minors = new ArrayList<User>();List<User> majors = new ArrayList<User>();

for (User u : users) {! if (u.getAge() < 18) {! ! minors.add(u);! } else {! ! majors.add(u);! }}

Page 35: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

val (minors, majors) = users.partition(_.age < 18)

Page 36: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

COLLECTION LIBRARY & FUNCTIONAL STYLE

val minors = users.filter(_.age < 18)

Page 37: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

•Minimal language, powerful library

• Language features for extensibility

EXTENSIBLE LANGUAGE

Page 38: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

DOMAIN SPECIFIC LANGUAGES

import collection.mutable.Stackimport org.scalatest._

class ExampleSpec extends FlatSpec with Matchers {

"A Stack" should "pop values in last-in-first-out order" in { val stack = new Stack[Int] stack.push(1) stack.push(2) stack.pop() should be (2) stack.pop() should be (1) }

it should "throw NoSuchElementException if an empty stack is popped" in { val emptyStack = new Stack[Int] a [NoSuchElementException] should be thrownBy { emptyStack.pop() } }}

Page 39: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

MACROSPLAY JSON DE/SERIALIZATION

Page 40: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

MACROSPLAY JSON DE/SERIALIZATION

case class Creature(name: String, isDead: Boolean, weight: Float)

implicit val creatureReads: Reads[Creature] = ( (__ \ "name").read[String] and (__ \ "isDead").read[Boolean] and (__ \ "weight").read[Float])(Creature)

implicit val creatureWrites: Writes[Creature] = ( (__ \ "name").write[String] and (__ \ "isDead").write[Boolean] and (__ \ "weight").write[Float])(unlift(Creature.unapply))

Page 41: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

MACROSPLAY JSON DE/SERIALIZATION

import play.api.json._

implicit val creatureFormat = Json.format[Creature] // format is a macro

Page 42: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

AGENDA

• History

•Why Scala?

• Scala in the wild

• The Code / Scala in practice

• Tools & more

Page 43: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

IDE

• IntelliJ IDEA

• Eclipse

• SublimeText

Page 44: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

SIMPLE BUILD TOOLname := "My Project"

version := "1.0"

organization := "org.myproject"

libraryDependencies += "org.scala-tools.testing" %% "scalacheck" % "1.8" % "test"

libraryDependencies ++= Seq( "net.databinder" %% "dispatch-meetup" % "0.7.8", "net.databinder" %% "dispatch-twitter" % "0.7.8")

javaOptions += "-Xmx256m"

logLevel in compile := Level.Warn

Page 45: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: AKKA

• Actor concurrency model based on Erlang

• “Human” design: actors talk to eachother and form hierarchies

•Much, much, much simpler to work and reason with than threads

Page 46: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: AKKA

Source: http://prabhubuzz.wordpress.com/2012/09/28/akka-really-mountains-of-concurrency/

Page 47: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: AKKAclass Master extends Actor {

! val workers = context.actorOf(Props[Worker].withRouter( ! RoundRobinRouter(nrOfInstances = 5))! )

! def receive = {! ! case Start =>! ! ! getDocumentsFromDb.foreach { document =>! ! ! ! workers ! Process(document)! ! ! }! ! case Result(processed) => writeResult(processed)! ! case Stop => children.foreach(stop)! }}

Page 48: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: AKKA

class Worker extends Actor {

! def receive = {

! ! case Process(doc: Document) =>! ! ! val processed = doSomeHardWork(doc)! ! ! sender ! Result(processed)! }

}

Page 49: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: PLAY

•MVC framework à la Rails

• Real-time web, streams (WebSocket, ...)

• Everything is compiled

• I mean everything: CSS, JavaScripts, Templates, URLs, JSON, ...

Page 50: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: PLAY

GET /users controllers.Users.listPOST /users controllers.Users.createPUT /users/:id/update controllers.Users.update(id: Long)DELETE /users/:id controllers.Users.delete(id: Long)

Page 51: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: PLAY

class Users extends Controller {

def list = Action { request => val users = User.findAll Ok(Json.toJson(users)) }

}

Page 52: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

FRAMEWORKS: PLAY

class Users extends Controller {

def list = Action { request => val users = User.findAll Ok(Json.toJson(users)) }

}200 OK

Content-Type: application/json

Page 53: Introduction to Scala

@elmanu Java Klassentreffen 2013 - javatraining.at

THANK YOU!

•Questions, comments ?

• http://logician.eu

[email protected]

•@elmanu