Scala, just a better java?

39
SCALA, JUST A BETTER JAVA? A quick talk to show you that there's much more

Transcript of Scala, just a better java?

SCALA,JUST A BETTER JAVA?

A quick talk to show you that there's much more

HELLO, MY NAME IS...Giampaolo Trapasso

@trapo1975

cosenonjaviste.it

blogzinga.it

WHY DO WE NEED A NEWLANGUAGE?

WELL..SOMETHING HAPPENED IN LAST 10~15YEARS

Cores 1 → 2 → 4 → ...

Server nodes 1 → 10's → 1000’s.

Response times seconds → milliseconds

Maintenance downtimes hours → nones

Data volum GBs → TBs and more

THE "RISE" OF THE FUNCTIONALPROGRAMMING (FP)

functions are used as the fundamental building blocks ofa programavoids changing-state and mutable datacalling a function f twice with the same value for anargument x will produce the same result f(x)easy scaling in and outmany deep interesting concepts that don't fit a life.. ehm..slide ;)

https://youtu.be/DJLDF6qZUX0

A BRIEF, INCOMPLETE, AND MOSTLY WRONGHISTORY OF PROGRAMMING LANGUAGES

2003 - A drunken Martin Odersky sees aReese's Peanut Butter Cup ad featuring

somebody's peanut butter getting onsomebody else's chocolate and has anidea. He creates Scala, a language that

unifies constructs from both object orientedand functional languages. This pisses offboth groups and each promptly declares

jihad.

SCALA - SCALABLE LANGUAGEblends Object Oriented and Functional Programming

powerful static type system (but feels dynamic)

concise and expressive syntax

compiles to Java byte code and runs on the JVM

interoperable with Java itself (both ways!)

ANOTHER HIPSTER STUFF?Twitter, LinkedIn, FourSquare, NASA, ..

Functional programming in Scala & Principles of ReactiveProgramming @ Coursera400K online students

http://www.quora.com/What-startups-or-tech-companies-are-using-Scala

ANOTHER *USA* HIPSTER STUFF?Lambdacon (Bologna) ~ 280 devScala Italy (Milano) ~ 150 + 70Scala Meetup (Milano) ~ 50G+ Community ~ 80

SHOW ME THE CODE"BASIC FEATURES"

SOME FEATURE WE'LL SEE/1

every value is an objectfunctions are "just" objectscompiler infer types (static typed)(almost) everything is an expressionevery operation is a method call

SOME FEATURE WE'LL SEE/2

language is designed to growcollectionstraitseasy singletonevery operation is a method call

CONCISE SYNTAX - JAVAPIZZA I

public class JavaPizza {

private Boolean tomato = true; private Boolean cheese = true; private Boolean ham = true; private String size = "NORMAL"; public JavaPizza(Boolean tomato, Boolean cheese, Boolean ham, String size) { this.setTomato(tomato); this.setCheese(cheese); this.setHam(ham); this.setSize(size); }

CONCISE SYNTAX - JAVAPIZZA/II

public Boolean getTomato() { return tomato; }

public void setTomato(Boolean tomato) { this.tomato = tomato; }

public Boolean getCheese() { return cheese; }

public void setCheese(Boolean cheese) { this.cheese = cheese; }

CONCISE SYNTAX - JAVAPIZZA/III

public Boolean getHam() {

return ham;

}

public void setHam(Boolean ham) {

this.ham = ham;

}

public String getSize() {

return size;

}

public void setSize(String size) {

this.size = size;

}

}

CONCISE SYNTAX - PIZZA

class Pizza(var tomato: Boolean = true,

var cheese: Boolean = true,

var ham: Boolean = true,

var size: String = "NORMAL")

everything is public by default, change it if neededvar => something you can change, val => somethingfinalspecify defaults if neededtypes are after parameterssetters and getters are generatedmember variables are private (uniform access principle)no semicolon needed

CREATING OBJECTS

val pizza = new Pizza(true, false, true, "HUGE") // type inference

is the same asval pizza : Pizza = new Pizza(true, false, true, "HUGE")

VAL != VARvar secondPizza = new Pizza(true, true, true, "NORMAL") secondPizza = new Pizza(false, false, true, "HUGE") // will compileval thirdPizza = new Pizza(true, false, true, "SMALL")thirdPizza = secondPizza // won't compile

var: side effect, OOP programming

val: no side effect, functional programming

DEFINING METHODSdef slice(numberOfPieces: Int): Unit = {

println(s"Pizza is in ${numberOfPieces} pieces")

}

a method starts with a defreturn type is optional (with a little exception)Unit ~ void in Javareturn keyword is optional, last expression will bereturnedplus: string interpolation

EXPRESSIVE SYNTAXval pizza1 = new Pizza(true, true, false, "NORMAL")val pizza2 = new Pizza(true, true)val pizza3 = new Pizza(tomato = true, ham = true, size = "HUGE", cheese = val pizza4 = new Pizza(size = "SMALL")

if parameters have default, you can omit them on rightyou can pass parameter using names (without order)you can pass only parameters you want using name, ifothers have defaultmore on classes:

cosenonjaviste.it/creare-una-classe-in-scala/

SINGLETONS/I

object Oven {

def cook(pizza: Pizza): Unit = {

println(s"Pizza $pizza is cooking")

Thread.sleep(1000)

println("Pizza is ready")

}

}

a singleton uses the object keyworkdpattern provided by the languageplus: a Java class used inside Scala

SINGLETONS/II

object Margherita extends Pizza(true, false, false, "NORMAL") {

override def toString = "Pizza Margherita"

}

Oven.cook(new Pizza())

println(Margherita.toString())

objects can extends classesevery overridden method must use override keyword

CASE CLASSEScase class Pizza(tomato: Boolean = true, cheese: Boolean = true, ham:

val p = Pizza(cheese = false) // the same as val p = new Pizza(cheese = false)

syntactic sugar, but usefulevery parameter is immutablea companion object is createdfactory, pattern matchingmore on http://cosenonjaviste.it/scala-le-case-class/

INHRERITANCE/I

trait PizzaMaker { def preparePizza(pizza: Pizza): String // this is abstract}

trait Waiter { def servePizza(pizza: Pizza) = println("this is your pizza")}

abstract class Worker { def greet = { println("I'm ready to work") }}

object Pino extends Worker with PizzaMaker with Waiter {...}

INHRERITANCE/II

a class can inherite only one other classtrait ~ Java 8 interfacea class can mix-in many traitstrait linearization resolves the diamond problem (mostly)

SHOW ME THE CODE"ADVANCES FEATURES"

PATTERN MATCHING/I

object Pino extends Worker with PizzaMaker {

def preparePizza(pizza: Pizza): String = {

pizza match {

case Pizza(false, cheese, ham, size) =>

"No tomato on this"

case Pizza(_, _, _, "SMALL") =>

"Little chamption, your pizza is coming"

case pizza@Margherita =>

s"I like your ${pizza.size} Margherita"

case _ => "OK"

}

}

}

PATTERN MATCHING/II

a super flexible Java switch (but very different innature)in love with case classes, but possible on every classcan match partial definition of objectscan match types_ is a wildcard

WORKING WITH COLLECTIONS ANDFUNCTIONS/I

val order = List(pizza1, pizza2, pizza3, pizza4, pizza5)

val noTomato: (Pizza => Boolean) = (p => p.tomato == false)

order .filter(noTomato) .filter(p => p.ham == true) .map(pizza => Pino.preparePizza(pizza)) .map(println)

WORKING WITH COLLECTIONS ANDFUNCTIONS/II

easy to create a collectionfunctions are objects, you can pass them aroundhigh order functionsyou can use methods as functionsfilter, map, fold and all the rest

OPERATORS ARE JUST METHODS (ANEXAMPLE)

case class Pizza(tomato: Boolean = true, cheese: Boolean = true, ham: Boolean =

def slice(numberOfPieces: Int) =

println(s"Pizza is in ${numberOfPieces} pieces")

def /(numberOfPieces: Int) = slice(numberOfPieces)

}

val pizza = Pizza()

pizza.slice(4)

pizza./(4)

pizza / 4

Simple rules to simplify syntax (towards DSL)

IMPLICITS/Iclass MargheritaList(val n: Int) {

def margheritas = { var list: List[Pizza] = List() for (i <- 1 to n) list = list :+ Margherita list }

}

using a var with an immutable listnote the genericsusing collection operator :+

IMPLICITS/IIval order = new MargheritaList(4).margheritas()

a bit verbose..let's introduce implicit conversionimplicit def fromIntToMargherita(n: Int) = new MargheritaList(n)

compiler implicity does conversion for usval order = 4.margheritas()

or betterval order = 4 margheritas

A PIZZA DSLval pizza = Margherita

Pino preparePizza pizza

Oven cook pizza

pizza / 6

Question. How much keywords do you see?

THE END

Thanks for following, slides and video onhttp://cosenonjaviste.it