SlideShare a Scribd company logo
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 NEW
LANGUAGE?
WELL..SOMETHING HAPPENED IN LAST 10~15
YEARS
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 FUNCTIONAL
PROGRAMMING (FP)
functions are used as the fundamental building blocks of
a program
avoids changing-state and mutable data
calling a function f twice with the same value for an
argument x will produce the same result f(x)
easy scaling in and out
many deep interesting concepts that don't fit a life.. ehm..
slide ;)
https://youtu.be/DJLDF6qZUX0
A BRIEF, INCOMPLETE, AND MOSTLY WRONG
HISTORY OF PROGRAMMING LANGUAGES
2003 - A drunken Martin Odersky sees a
Reese's Peanut Butter Cup ad featuring
somebody's peanut butter getting on
somebody else's chocolate and has an
idea. He creates Scala, a language that
unifies constructs from both object oriented
and functional languages. This pisses off
both groups and each promptly declares
jihad.
SCALA - SCALABLE LANGUAGE
blends 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 Reactive
Programming @ Coursera
400K online students
http://www.quora.com/What-startups-or-tech-
companies-are-using-Scala
ANOTHER *USA* HIPSTER STUFF?
Lambdacon (Bologna) ~ 280 dev
Scala Italy (Milano) ~ 150 + 70
Scala Meetup (Milano) ~ 50
G+ Community ~ 80
SHOW ME THE CODE
"BASIC FEATURES"
SOME FEATURE WE'LL SEE/1
every value is an object
functions are "just" objects
compiler infer types (static typed)
(almost) everything is an expression
every operation is a method call
SOME FEATURE WE'LL SEE/2
language is designed to grow
collections
traits
easy singleton
every 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 needed
var => something you can change, val => something
final
specify defaults if needed
types are after parameters
setters and getters are generated
member variables are private (uniform access principle)
no semicolon needed
CREATING OBJECTS
val pizza = new Pizza(true, false, true, "HUGE") // type inference
is the same as
val pizza : Pizza = new Pizza(true, false, true, "HUGE")
VAL != VAR
var secondPizza = new Pizza(true, true, true, "NORMAL")
secondPizza = new Pizza(false, false, true, "HUGE") // will compile
val thirdPizza = new Pizza(true, false, true, "SMALL")
thirdPizza = secondPizza // won't compile
var: side effect, OOP programming
val: no side effect, functional programming
DEFINING METHODS
def slice(numberOfPieces: Int): Unit = {
println(s"Pizza is in ${numberOfPieces} pieces")
}
a method starts with a def
return type is optional (with a little exception)
Unit ~ void in Java
return keyword is optional, last expression will be
returned
plus: string interpolation
EXPRESSIVE SYNTAX
val 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 right
you can pass parameter using names (without order)
you can pass only parameters you want using name, if
others have default
more 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 keyworkd
pattern provided by the language
plus: 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 classes
every overridden method must use override keyword
CASE CLASSES
case 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 useful
every parameter is immutable
a companion object is created
factory, pattern matching
more 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 class
trait ~ Java 8 interface
a class can mix-in many traits
trait 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 in
nature)
in love with case classes, but possible on every class
can match partial definition of objects
can match types
_ is a wildcard
WORKING WITH COLLECTIONS AND
FUNCTIONS/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 AND
FUNCTIONS/II
easy to create a collection
functions are objects, you can pass them around
high order functions
you can use methods as functions
filter, map, fold and all the rest
OPERATORS ARE JUST METHODS (AN
EXAMPLE)
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/I
class 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 list
note the generics
using collection operator :+
IMPLICITS/II
val order = new MargheritaList(4).margheritas()
a bit verbose..let's introduce implicit conversion
implicit def fromIntToMargherita(n: Int) = new MargheritaList(n)
compiler implicity does conversion for us
val order = 4.margheritas()
or better
val order = 4 margheritas
A PIZZA DSL
val 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 on
http://cosenonjaviste.it

More Related Content

What's hot

Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
Jarek Ratajski
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Anton Shemerey
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
Ryan McGeary
 
Kotlin Collections
Kotlin CollectionsKotlin Collections
Kotlin Collections
Halil Özcan
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
Chang W. Doh
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
Adam Dudczak
 
Swift internals
Swift internalsSwift internals
Swift internals
Jung Kim
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기
Taehwan kwon
 
Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜
Kiyotaka Oku
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
Juriy Zaytsev
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
Pawel Szulc
 
Coffee script
Coffee scriptCoffee script
Coffee script
timourian
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
Pawel Szulc
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
Ahmad Arif Faizin
 
Google guava
Google guavaGoogle guava
Ff to-fp
Ff to-fpFf to-fp
Ff to-fp
Andy Petrella
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
Robert Lujo
 

What's hot (20)

Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code styleRuby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
Ruby: OOP, metaprogramming, blocks, iterators, mix-ins, duck typing. Code style
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Kotlin Collections
Kotlin CollectionsKotlin Collections
Kotlin Collections
 
Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요Kotlin, 어떻게 동작하나요
Kotlin, 어떻게 동작하나요
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기Kotlin으로 안드로이드 개발하기
Kotlin으로 안드로이드 개발하기
 
Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜Griffon不定期便〜G*ワークショップ編〜
Griffon不定期便〜G*ワークショップ編〜
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Fun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming languageFun never stops. introduction to haskell programming language
Fun never stops. introduction to haskell programming language
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Google guava
Google guavaGoogle guava
Google guava
 
Ff to-fp
Ff to-fpFf to-fp
Ff to-fp
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 

Similar to Scala, just a better java?

Factory and Abstract Factory
Factory and Abstract FactoryFactory and Abstract Factory
Factory and Abstract Factory
Jonathan Simon
 
Design patterns
Design patternsDesign patterns
Design patterns
Rajat Arora
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
William Myers
 
Functions
FunctionsFunctions
Functions
Chris Huie
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonML
Riza Fahmi
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
Riza Fahmi
 
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Mike Nakhimovich
 
Weapons for Boilerplate Destruction
Weapons for Boilerplate DestructionWeapons for Boilerplate Destruction
Weapons for Boilerplate Destruction
Everyware Technologies
 
Total World Domination with i18n (es)
Total World Domination with i18n (es)Total World Domination with i18n (es)
Total World Domination with i18n (es)
Zé Fontainhas
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
Samir Talwar
 
MySQL Large Table Schema Changes
MySQL Large Table Schema ChangesMySQL Large Table Schema Changes
MySQL Large Table Schema Changes
Bill Sickles
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
Software Guru
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
Christian Trabold
 
Order pizza from Boxee
Order pizza from BoxeeOrder pizza from Boxee
Order pizza from Boxee
Daniel Johnson
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
DroidConTLV
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
✅ William Pinaud
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
Bartłomiej Kiełbasa
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
myrajendra
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
Peter Higgins
 
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
martinlippert
 

Similar to Scala, just a better java? (20)

Factory and Abstract Factory
Factory and Abstract FactoryFactory and Abstract Factory
Factory and Abstract Factory
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Fewd week5 slides
Fewd week5 slidesFewd week5 slides
Fewd week5 slides
 
Functions
FunctionsFunctions
Functions
 
Introduction to ReasonML
Introduction to ReasonMLIntroduction to ReasonML
Introduction to ReasonML
 
Perkenalan ReasonML
Perkenalan ReasonMLPerkenalan ReasonML
Perkenalan ReasonML
 
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
Data Loading Made Easy with Mike Nakhimovich DroidCon Italy 2017
 
Weapons for Boilerplate Destruction
Weapons for Boilerplate DestructionWeapons for Boilerplate Destruction
Weapons for Boilerplate Destruction
 
Total World Domination with i18n (es)
Total World Domination with i18n (es)Total World Domination with i18n (es)
Total World Domination with i18n (es)
 
Design patterns in the 21st Century
Design patterns in the 21st CenturyDesign patterns in the 21st Century
Design patterns in the 21st Century
 
MySQL Large Table Schema Changes
MySQL Large Table Schema ChangesMySQL Large Table Schema Changes
MySQL Large Table Schema Changes
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
Order pizza from Boxee
Order pizza from BoxeeOrder pizza from Boxee
Order pizza from Boxee
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
Menu bars and menus
Menu bars and menusMenu bars and menus
Menu bars and menus
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
EclipseCon-Europe 2013: Optimizing performance - how to make your Eclipse-bas...
 

Recently uploaded

DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
Yara Milbes
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 

Recently uploaded (20)

DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
SMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API ServiceSMS API Integration in Saudi Arabia| Best SMS API Service
SMS API Integration in Saudi Arabia| Best SMS API Service
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 

Scala, just a better java?

  • 1. SCALA, JUST A BETTER JAVA? A quick talk to show you that there's much more
  • 2. HELLO, MY NAME IS... Giampaolo Trapasso @trapo1975 cosenonjaviste.it blogzinga.it
  • 3. WHY DO WE NEED A NEW LANGUAGE?
  • 4.
  • 5.
  • 6.
  • 7. WELL..SOMETHING HAPPENED IN LAST 10~15 YEARS 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
  • 8. THE "RISE" OF THE FUNCTIONAL PROGRAMMING (FP) functions are used as the fundamental building blocks of a program avoids changing-state and mutable data calling a function f twice with the same value for an argument x will produce the same result f(x) easy scaling in and out many deep interesting concepts that don't fit a life.. ehm.. slide ;)
  • 10. A BRIEF, INCOMPLETE, AND MOSTLY WRONG HISTORY OF PROGRAMMING LANGUAGES 2003 - A drunken Martin Odersky sees a Reese's Peanut Butter Cup ad featuring somebody's peanut butter getting on somebody else's chocolate and has an idea. He creates Scala, a language that unifies constructs from both object oriented and functional languages. This pisses off both groups and each promptly declares jihad.
  • 11. SCALA - SCALABLE LANGUAGE blends 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!)
  • 12. ANOTHER HIPSTER STUFF? Twitter, LinkedIn, FourSquare, NASA, .. Functional programming in Scala & Principles of Reactive Programming @ Coursera 400K online students http://www.quora.com/What-startups-or-tech- companies-are-using-Scala
  • 13. ANOTHER *USA* HIPSTER STUFF? Lambdacon (Bologna) ~ 280 dev Scala Italy (Milano) ~ 150 + 70 Scala Meetup (Milano) ~ 50 G+ Community ~ 80
  • 14. SHOW ME THE CODE "BASIC FEATURES"
  • 15. SOME FEATURE WE'LL SEE/1 every value is an object functions are "just" objects compiler infer types (static typed) (almost) everything is an expression every operation is a method call
  • 16. SOME FEATURE WE'LL SEE/2 language is designed to grow collections traits easy singleton every operation is a method call
  • 17. 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); }
  • 18. 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; }
  • 19. 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; } }
  • 20. 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 needed var => something you can change, val => something final specify defaults if needed types are after parameters setters and getters are generated member variables are private (uniform access principle) no semicolon needed
  • 21. CREATING OBJECTS val pizza = new Pizza(true, false, true, "HUGE") // type inference is the same as val pizza : Pizza = new Pizza(true, false, true, "HUGE")
  • 22. VAL != VAR var secondPizza = new Pizza(true, true, true, "NORMAL") secondPizza = new Pizza(false, false, true, "HUGE") // will compile val thirdPizza = new Pizza(true, false, true, "SMALL") thirdPizza = secondPizza // won't compile var: side effect, OOP programming val: no side effect, functional programming
  • 23. DEFINING METHODS def slice(numberOfPieces: Int): Unit = { println(s"Pizza is in ${numberOfPieces} pieces") } a method starts with a def return type is optional (with a little exception) Unit ~ void in Java return keyword is optional, last expression will be returned plus: string interpolation
  • 24. EXPRESSIVE SYNTAX val 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 right you can pass parameter using names (without order) you can pass only parameters you want using name, if others have default more on classes: cosenonjaviste.it/creare-una-classe-in-scala/
  • 25. 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 keyworkd pattern provided by the language plus: a Java class used inside Scala
  • 26. 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 classes every overridden method must use override keyword
  • 27. CASE CLASSES case 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 useful every parameter is immutable a companion object is created factory, pattern matching more on http://cosenonjaviste.it/scala-le-case-class/
  • 28. 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 {...}
  • 29. INHRERITANCE/II a class can inherite only one other class trait ~ Java 8 interface a class can mix-in many traits trait linearization resolves the diamond problem (mostly)
  • 30. SHOW ME THE CODE "ADVANCES FEATURES"
  • 31. 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" } } }
  • 32. PATTERN MATCHING/II a super flexible Java switch (but very different in nature) in love with case classes, but possible on every class can match partial definition of objects can match types _ is a wildcard
  • 33. WORKING WITH COLLECTIONS AND FUNCTIONS/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)
  • 34. WORKING WITH COLLECTIONS AND FUNCTIONS/II easy to create a collection functions are objects, you can pass them around high order functions you can use methods as functions filter, map, fold and all the rest
  • 35. OPERATORS ARE JUST METHODS (AN EXAMPLE) 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)
  • 36. IMPLICITS/I class 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 list note the generics using collection operator :+
  • 37. IMPLICITS/II val order = new MargheritaList(4).margheritas() a bit verbose..let's introduce implicit conversion implicit def fromIntToMargherita(n: Int) = new MargheritaList(n) compiler implicity does conversion for us val order = 4.margheritas() or better val order = 4 margheritas
  • 38. A PIZZA DSL val pizza = Margherita Pino preparePizza pizza Oven cook pizza pizza / 6 Question. How much keywords do you see?
  • 39. THE END Thanks for following, slides and video on http://cosenonjaviste.it