SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Scala taxonomy explained
from Java programmer
Radim.Pavlicek@gmail.com
Agenda
● OO Features
● Pattern matching
● Functional Programming
● Actors
● Futures
● Implicits
Data Transfer Objets
class Person {
private String firstName;
String getFirstName() {
return firstName;
}
void setFirstName(String aFirstName) {
this.firstName = aFirstName;
}
}
toString
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + ''' +
", lastName='" + lastName + ''' +
'}';
}
equals
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
if (!firstName.equals(person.firstName))
return false;
if (!lastName.equals(person.lastName))
return false;
return true
}
hashCode
@Override
public int hashCode() {
int result = firstName.hashCode();
result = 31 * result + lastName.hashCode();
return result;
}
Builder
static class Builder {
String aName = "Radim";
Builder withFirstName(String aName) {
this.name = aName; return this;
}
Person build() {
Person p = new Person; p.setName(aName);
return p;
}
Case Classes
case class Person(firstName: String =
"Bill", lastName :String = "Gates")
val me = Person(lastName = "Crosby")
● Immutable
● toString, equals, hashCode
● person.copy(lastName="Malkin")
Laziness in Java
Integer cached = null;
Integer getExpensiveComputation() {
if (null == cached) {
cached = doCount();
}
return cached;
}
Lazy Definition
lazy val count = doCount()
Imports
import scala.collection.immutable.Map
object HelloWorld {
def main(args: Array[String]) {
import scala.collection.immutable.
{Map=>MobNumbers}
val my : MobNumbers[String, String] =
MobileNumbers("radim" -> "6767982408")
Console.print( my("radim") )
}
}
Java: Singletons
public class Singleton {
private Singleton INSTANCE = null;
private Singleton() {}
public Singleton getInstance() {
if (null == INSTANCE) {
INSTANCE = new Singleton()
}
}
Objects
class CompanionObjects(val id: Long, val
description: String = "")
object CompanionObjects{
def zero = new CompanionObjects(id = 0,
description = "zero")
def apply(id:Int, description:String)= new
CompanionObjets(id,description)
def one = CompanionObjets(1, "one")
val errorMessage = "ID should be positive"
}
Pattern matching
In Java:
Switch statements with String cases have
been implemented in Java SE 7, at least 16
years after they were first requested.
Pattern matching
object Matching extends App {
val name :AnyRef= ...
name match {
case "Radim" => println("me")
case "crosby" | "sidney" => println("NHL")
case Seq("sidney", _) => println("sidney with
someone")
case Seq("sidney", _*) => println("sidney with group")
case x: Int if x < 0 => println("negative number")
case y => println("Unknown " + y)
}
}
scala.annotation.switch
(ch: @switch) match {
case 'a' if eof => println("a with oef")
case 'b' => println("b")
case 'c' => println("c")
}
Functional programming
Immutability
Java
String, BigDecimal
Scala
val immutable = 1
var mutable = 2
mutable = 3
Immutability cont.
val n = "123".reverse
val m = n.reverse
println(n, m) // 321, 123
val o = new StringBuffer("123").reverse()
val p = o.reverse()
println(o, p) // 123, 123
Higher order functions
object Collections extends App{
val c = 4 to 8
val s: IndexedSeq[String] = c map(_+"th")
s map (_.toUpperCase)
println(s) //4th, 5th, 6th, 7th, 8th
}
Parallel collection
object Parralel extends App{
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0)/1000000 + " ms")
result
}
val c = 1 to 10000000
time { c map (_ + 1) } //4935 ms
time { c.par map (_ + 1) } //3723 ms
}
Currying
object Curry extends App{
def product(i: Int)(j: Int) = i * j
def times2 = product(2)_
def times3 = product(3)_
println(times2 (4)) //8
println(times3 (4)) //12
}
Partial functions
val sample = 1 to 10
val isEven: PartialFunction[Int, String] =
{case x if x % 2 == 0 => x+" is even"}
// the method collect can use isDefinedAt
to select which members to collect
val evenNumbers = sample collect isEven
println(evenNumbers)
Actors
Futures
import ExecutionContext.Implicits.global
object Futures extends App {
@volatile var totalA = 0
val text = Future {
Thread.sleep(1000); val a = "a" * 16
}
text onSuccess {
case txt => totalA += txt.count(_ == 'a')
}
println(totalA) // 0
Thread.sleep(1000); println(totalA) //0
Thread.sleep(1000); println(totalA) //16
}
Implicit conversions
Java:
String.valueOf(int i),
Integer.parseInt(String s)
Scala:
(1 to 4).foreach(println)
Implicit parameters
object ImplicitParam extends App{
def max[T](a: T, b: T)(implicit $ev1: Ordering[T]): T =
..
class Timeout(val milis: Int)
object Timeout {
def apply(milis: Int) = new Timeout(milis)
implicit val t: Timeout = Timeout(10)
}
def query(i: Int)(implicit t: Timeout) {
println(t.milis)
}
query(1)
To be continued...

Contenu connexe

Tendances

Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 

Tendances (20)

The Ring programming language version 1.7 book - Part 34 of 196
The Ring programming language version 1.7 book - Part 34 of 196The Ring programming language version 1.7 book - Part 34 of 196
The Ring programming language version 1.7 book - Part 34 of 196
 
The Ring programming language version 1.6 book - Part 183 of 189
The Ring programming language version 1.6 book - Part 183 of 189The Ring programming language version 1.6 book - Part 183 of 189
The Ring programming language version 1.6 book - Part 183 of 189
 
The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181The Ring programming language version 1.5.2 book - Part 32 of 181
The Ring programming language version 1.5.2 book - Part 32 of 181
 
Introduction to-scala
Introduction to-scalaIntroduction to-scala
Introduction to-scala
 
The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189The Ring programming language version 1.6 book - Part 40 of 189
The Ring programming language version 1.6 book - Part 40 of 189
 
The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84The Ring programming language version 1.2 book - Part 22 of 84
The Ring programming language version 1.2 book - Part 22 of 84
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180The Ring programming language version 1.5.1 book - Part 36 of 180
The Ring programming language version 1.5.1 book - Part 36 of 180
 
The Ring programming language version 1.5.2 book - Part 30 of 181
The Ring programming language version 1.5.2 book - Part 30 of 181The Ring programming language version 1.5.2 book - Part 30 of 181
The Ring programming language version 1.5.2 book - Part 30 of 181
 
The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84The Ring programming language version 1.2 book - Part 20 of 84
The Ring programming language version 1.2 book - Part 20 of 84
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180The Ring programming language version 1.5.1 book - Part 29 of 180
The Ring programming language version 1.5.1 book - Part 29 of 180
 
Java cheatsheet
Java cheatsheetJava cheatsheet
Java cheatsheet
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185The Ring programming language version 1.5.4 book - Part 33 of 185
The Ring programming language version 1.5.4 book - Part 33 of 185
 
Ruslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testingRuslan Shevchenko - Property based testing
Ruslan Shevchenko - Property based testing
 
The Ring programming language version 1.7 book - Part 40 of 196
The Ring programming language version 1.7 book - Part 40 of 196The Ring programming language version 1.7 book - Part 40 of 196
The Ring programming language version 1.7 book - Part 40 of 196
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
The Ring programming language version 1.4 book - Part 29 of 30
The Ring programming language version 1.4 book - Part 29 of 30The Ring programming language version 1.4 book - Part 29 of 30
The Ring programming language version 1.4 book - Part 29 of 30
 
The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185The Ring programming language version 1.5.4 book - Part 31 of 185
The Ring programming language version 1.5.4 book - Part 31 of 185
 

En vedette

Tjänster.unicode
Tjänster.unicodeTjänster.unicode
Tjänster.unicode
Sari Salmi
 
Procurement Intelligence Priming Procurement Leaders for Business Power Play
Procurement Intelligence  Priming Procurement Leaders for Business Power PlayProcurement Intelligence  Priming Procurement Leaders for Business Power Play
Procurement Intelligence Priming Procurement Leaders for Business Power Play
Beroe Inc - Advantage Procurement
 

En vedette (20)

Web ui testing
Web ui testingWeb ui testing
Web ui testing
 
Internal combustion engine
Internal combustion engineInternal combustion engine
Internal combustion engine
 
Encontro com escritor joão morgado
Encontro com escritor joão morgadoEncontro com escritor joão morgado
Encontro com escritor joão morgado
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Tjänster.unicode
Tjänster.unicodeTjänster.unicode
Tjänster.unicode
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
Genetically Modified Soybean Seed Patent Expiry
Genetically Modified Soybean Seed Patent ExpiryGenetically Modified Soybean Seed Patent Expiry
Genetically Modified Soybean Seed Patent Expiry
 
Procurement Intelligence Priming Procurement Leaders for Business Power Play
Procurement Intelligence  Priming Procurement Leaders for Business Power PlayProcurement Intelligence  Priming Procurement Leaders for Business Power Play
Procurement Intelligence Priming Procurement Leaders for Business Power Play
 
3D Printing: An emerging trend and its impact on the MRO supply chain | Beroe...
3D Printing: An emerging trend and its impact on the MRO supply chain | Beroe...3D Printing: An emerging trend and its impact on the MRO supply chain | Beroe...
3D Printing: An emerging trend and its impact on the MRO supply chain | Beroe...
 
J unit introduction
J unit introductionJ unit introduction
J unit introduction
 
Conflict Minerals - A Supply Chain Check for Electronic OEMs Industry
Conflict Minerals - A Supply Chain Check for Electronic OEMs IndustryConflict Minerals - A Supply Chain Check for Electronic OEMs Industry
Conflict Minerals - A Supply Chain Check for Electronic OEMs Industry
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Scala functions
Scala functionsScala functions
Scala functions
 
Brazil telecom market next treasure trove for MVNO's
Brazil telecom market next treasure trove for MVNO'sBrazil telecom market next treasure trove for MVNO's
Brazil telecom market next treasure trove for MVNO's
 
Will china remain a low cost country?
Will china remain a low cost country?Will china remain a low cost country?
Will china remain a low cost country?
 
The Future of Procurement - End of Business as Usual
The Future of Procurement - End of Business as UsualThe Future of Procurement - End of Business as Usual
The Future of Procurement - End of Business as Usual
 
China's Resources Acquisition
China's Resources AcquisitionChina's Resources Acquisition
China's Resources Acquisition
 
Genome editing tools article
Genome editing tools   articleGenome editing tools   article
Genome editing tools article
 
Nagoya Protocol and its Implications on Pharmaceutical Industry
Nagoya Protocol and its Implications on Pharmaceutical IndustryNagoya Protocol and its Implications on Pharmaceutical Industry
Nagoya Protocol and its Implications on Pharmaceutical Industry
 
Propy-LENE Supply! Go Green! On-Purpose Technologies for the Future
Propy-LENE Supply! Go Green! On-Purpose Technologies for the FuturePropy-LENE Supply! Go Green! On-Purpose Technologies for the Future
Propy-LENE Supply! Go Green! On-Purpose Technologies for the Future
 

Similaire à Scala taxonomy

Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 

Similaire à Scala taxonomy (20)

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala
ScalaScala
Scala
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
Extractors & Implicit conversions
Extractors & Implicit conversionsExtractors & Implicit conversions
Extractors & Implicit conversions
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Scala taxonomy

  • 1. Scala taxonomy explained from Java programmer Radim.Pavlicek@gmail.com
  • 2. Agenda ● OO Features ● Pattern matching ● Functional Programming ● Actors ● Futures ● Implicits
  • 3. Data Transfer Objets class Person { private String firstName; String getFirstName() { return firstName; } void setFirstName(String aFirstName) { this.firstName = aFirstName; } }
  • 4. toString @Override public String toString() { return "Person{" + "firstName='" + firstName + ''' + ", lastName='" + lastName + ''' + '}'; }
  • 5. equals @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; if (!firstName.equals(person.firstName)) return false; if (!lastName.equals(person.lastName)) return false; return true }
  • 6. hashCode @Override public int hashCode() { int result = firstName.hashCode(); result = 31 * result + lastName.hashCode(); return result; }
  • 7. Builder static class Builder { String aName = "Radim"; Builder withFirstName(String aName) { this.name = aName; return this; } Person build() { Person p = new Person; p.setName(aName); return p; }
  • 8. Case Classes case class Person(firstName: String = "Bill", lastName :String = "Gates") val me = Person(lastName = "Crosby") ● Immutable ● toString, equals, hashCode ● person.copy(lastName="Malkin")
  • 9. Laziness in Java Integer cached = null; Integer getExpensiveComputation() { if (null == cached) { cached = doCount(); } return cached; }
  • 10. Lazy Definition lazy val count = doCount()
  • 11. Imports import scala.collection.immutable.Map object HelloWorld { def main(args: Array[String]) { import scala.collection.immutable. {Map=>MobNumbers} val my : MobNumbers[String, String] = MobileNumbers("radim" -> "6767982408") Console.print( my("radim") ) } }
  • 12. Java: Singletons public class Singleton { private Singleton INSTANCE = null; private Singleton() {} public Singleton getInstance() { if (null == INSTANCE) { INSTANCE = new Singleton() } }
  • 13. Objects class CompanionObjects(val id: Long, val description: String = "") object CompanionObjects{ def zero = new CompanionObjects(id = 0, description = "zero") def apply(id:Int, description:String)= new CompanionObjets(id,description) def one = CompanionObjets(1, "one") val errorMessage = "ID should be positive" }
  • 14. Pattern matching In Java: Switch statements with String cases have been implemented in Java SE 7, at least 16 years after they were first requested.
  • 15. Pattern matching object Matching extends App { val name :AnyRef= ... name match { case "Radim" => println("me") case "crosby" | "sidney" => println("NHL") case Seq("sidney", _) => println("sidney with someone") case Seq("sidney", _*) => println("sidney with group") case x: Int if x < 0 => println("negative number") case y => println("Unknown " + y) } }
  • 16. scala.annotation.switch (ch: @switch) match { case 'a' if eof => println("a with oef") case 'b' => println("b") case 'c' => println("c") }
  • 19. Immutability cont. val n = "123".reverse val m = n.reverse println(n, m) // 321, 123 val o = new StringBuffer("123").reverse() val p = o.reverse() println(o, p) // 123, 123
  • 20. Higher order functions object Collections extends App{ val c = 4 to 8 val s: IndexedSeq[String] = c map(_+"th") s map (_.toUpperCase) println(s) //4th, 5th, 6th, 7th, 8th }
  • 21. Parallel collection object Parralel extends App{ def time[R](block: => R): R = { val t0 = System.nanoTime() val result = block // call-by-name val t1 = System.nanoTime() println("Elapsed time: " + (t1 - t0)/1000000 + " ms") result } val c = 1 to 10000000 time { c map (_ + 1) } //4935 ms time { c.par map (_ + 1) } //3723 ms }
  • 22. Currying object Curry extends App{ def product(i: Int)(j: Int) = i * j def times2 = product(2)_ def times3 = product(3)_ println(times2 (4)) //8 println(times3 (4)) //12 }
  • 23. Partial functions val sample = 1 to 10 val isEven: PartialFunction[Int, String] = {case x if x % 2 == 0 => x+" is even"} // the method collect can use isDefinedAt to select which members to collect val evenNumbers = sample collect isEven println(evenNumbers)
  • 25. Futures import ExecutionContext.Implicits.global object Futures extends App { @volatile var totalA = 0 val text = Future { Thread.sleep(1000); val a = "a" * 16 } text onSuccess { case txt => totalA += txt.count(_ == 'a') } println(totalA) // 0 Thread.sleep(1000); println(totalA) //0 Thread.sleep(1000); println(totalA) //16 }
  • 27. Implicit parameters object ImplicitParam extends App{ def max[T](a: T, b: T)(implicit $ev1: Ordering[T]): T = .. class Timeout(val milis: Int) object Timeout { def apply(milis: Int) = new Timeout(milis) implicit val t: Timeout = Timeout(10) } def query(i: Int)(implicit t: Timeout) { println(t.milis) } query(1)