Top Banner
SCALA, JUST A BETTER JAVA? A quick talk to show you that there's much more
39
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Scala, just a better java?

SCALA,JUST A BETTER JAVA?

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

Page 2: Scala, just a better java?

HELLO, MY NAME IS...Giampaolo Trapasso

@trapo1975

cosenonjaviste.it

blogzinga.it

Page 3: Scala, just a better java?

WHY DO WE NEED A NEWLANGUAGE?

Page 4: Scala, just a better java?
Page 5: Scala, just a better java?
Page 6: Scala, just a better java?
Page 7: Scala, just a better java?

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

Page 8: Scala, just a better java?

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 ;)

Page 9: Scala, just a better java?

https://youtu.be/DJLDF6qZUX0

Page 10: Scala, just a better java?

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.

Page 11: Scala, just a better java?

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!)

Page 12: Scala, just a better java?

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

Page 13: Scala, just a better java?

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

Page 14: Scala, just a better java?

SHOW ME THE CODE"BASIC FEATURES"

Page 15: Scala, just a better java?

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

Page 16: Scala, just a better java?

SOME FEATURE WE'LL SEE/2

language is designed to growcollectionstraitseasy singletonevery operation is a method call

Page 17: Scala, just a better java?

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); }

Page 18: Scala, just a better java?

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; }

Page 19: Scala, just a better java?

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;

}

}

Page 20: Scala, just a better java?

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

Page 21: Scala, just a better java?

CREATING OBJECTS

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

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

Page 22: Scala, just a better java?

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

Page 23: Scala, just a better java?

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

Page 24: Scala, just a better java?

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/

Page 25: Scala, just a better java?

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

Page 26: Scala, just a better java?

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

Page 27: Scala, just a better java?

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/

Page 28: Scala, just a better java?

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 {...}

Page 29: Scala, just a better java?

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)

Page 30: Scala, just a better java?

SHOW ME THE CODE"ADVANCES FEATURES"

Page 31: Scala, just a better java?

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"

}

}

}

Page 32: Scala, just a better java?

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

Page 33: Scala, just a better java?

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)

Page 34: Scala, just a better java?

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

Page 35: Scala, just a better java?

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)

Page 36: Scala, just a better java?

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 :+

Page 37: Scala, just a better java?

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

Page 38: Scala, just a better java?

A PIZZA DSLval pizza = Margherita

Pino preparePizza pizza

Oven cook pizza

pizza / 6

Question. How much keywords do you see?

Page 39: Scala, just a better java?

THE END

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