SlideShare une entreprise Scribd logo
1  sur  31
Clean Code Scala Scala == Effective Java ?
„Leave camp cleaner  than you found it.” Uncle Bob
Why do we write bad code ??? Rush (duck tape programmer) Laziness Careless We don’t know how good code looks like Lack of resources We like to do new things (create)
„Its harder to read the  code  than to write it” Joel Spolsky
How to improve work quality ? Dont give developers money rewardsbigger reward == worse performance Let them work on what they like and how they like (Google, Atlassian, Facebook) Allow and encourage self improvement
Java dev libraries Google Guava Apache Commons Spring Guice Scala !
Why Scala ? More concise More powerfull Fun! Fast Becoming popular !
Who uses Scala already
Class Parameters - Java publicclass Person { 	private String name; 	privateintage; publicPerson(String name, int age) { 		this.name = name; 		this.age = age; 	} 	public String getName() { 		returnname; 	} 	publicvoid setName(String name) { 		this.name = name; 	} 	publicint getAge() { 		returnage; 	} 	publicvoid setAge(int age) { 		this.age = age; 	} }
Class Parameters - Scala classPerson(var name: String, var age: Int)
publicclass Person { private String name; privateintage; public Person(String name, int age) { this.name = name; this.age = age; 	} public String getName() { returnname; 	} publicvoidsetName(String name) { this.name = name; 	} publicintgetAge() { returnage; 	} publicvoidsetAge(int age) { this.age = age; 	} @Override public String toString() { returnString.format("Person: %s age: %s", name, age); 	} @Override publicinthashCode() { inthashCode = 0; for(char c: name.toCharArray()) { hashCode += c; 		} return 11 * hashCode + age;  	} @Override publicboolean equals(Object other) { if(other == null) returnfalse; if(other instanceof Person) { 			Person person = (Person)other; returnperson.name.equals(name) && person.age == age; } returnfalse; 	}
Scala case class caseclass Person(name: String, age: Int) Dostajemy za darmo: equals(), hashCode() oraz toString() oraz niezmienną klasę (immutable).
To equal or not to equal ?  		Person p = new Person("Jan Kowalski", 30); 		Set<Person> set = new HashSet<Person>(); 		set.add(p); 		System.out.println(set.contains(p));  // true p.setAge(p.getAge()+1); System.out.println(set.contains(p));  // false 		... WTF ???
To equal or not to equal ? Iterator<Person> it = set.iterator(); booleancontainedP = false; while (it.hasNext()) { 		    Person nextP = it.next(); if (nextP.equals(p)) { containedP = true; break; 		    } 		} System.out.println(containedP);  // true  		// ... ???
Scala Case Class classPerson(val name: String, val age: Int) objectPerson { def apply(name: String, age: Int) = newPerson(name, age) // defhashCode(): Int // deftoString(): String // def equals(other: Object): Boolean defunapply(p: Person): Option[(String, Int)]=Some(p.name, p.age)  } ,[object Object],case
Java – working with Person Object x = new Person("Bill Clinton", 64); if(x instanceof Person) { 	Person p = (Person)x; 	System.out.println(„Person name: "+p.getName()); } else { 	System.out.println("Not a person"); } x = "Lukasz Kuczera"; if(x instanceof Person) { 	Person p = (Person)x; 	System.out.println("hello "+p.getName()); } elseif(x instanceof String) { 	String s = (String)x; if(s.equals("Bill Clinton"))  		System.out.println("Hello Bill"); else System.out.println("hello: "+s); } else System.out.println("err, ???");
Scala – Pattern Matching var x: Any = Person("Lukasz", 28); 	x match { case Person(name, age) => println("Person name: "+name); case _ => println("Not a person") } 	x = "Lukasz Kuczera" 	x match { case Person(name, age) => println("Person name: "+name) case"Bill Clinton" => println("hello Bill") case s: String => println("hello "+s) case _ => "err, ???" 	} Person name: Lukasz hello Lukasz Kuczera
Parameter validation publicclass Person { 	private String name; 	privateintage; publicPerson(String name, int age) { if(name == null) { thrownew NullPointerException(); } if(age < 0) { thrownew IllegalArgumentException("Age < 0") } 		this.name = name; 		this.age = age; 	}
Parameter validation caseclass Person(name: String, age: Int) { // @elidable(ASSERTION)assert(age > 0, "Age < 0")// by name parameter }
Working with arrays Java publicclass Partition { Person[] all; Person[] adults; Person[] minors; 	 {  ArrayList<Person> minorsList = new ArrayList<Person>(); ArrayList<Person> adultsList = new ArrayList<Person>(); for(int i=0; i<all.length; i++ ) { 	(all[i].age<18 ? adultsList: minorsList).add(all[i]); 	 	} 		minors = (Person[]) minorsList.toArray(); 		adults = (Person[]) adultsList.toArray(); } }
Working with arrays Scala val all: Array[Person] val (minors, adults) = all.partition(_.age<18)
Null’s – Java Map<String, String> capitals =  new HashMap<String, String>(); capitals.put("Poland", "Warsaw"); System.out.println(capitals.get("Polska").trim()); Exception in thread "main" java.lang.NullPointerException
Null’s - Scala   val capitals = Map("Poland" -> "Warsaw"); val capitalOption: Option[String] = capitals.get("Polska")   capitalOption match { case Some(value) => println(value) case None => println("Not found") case _ =>   } if(capitalOption.isDefined) println(capitalOption.get)   println(capitalOption getOrElse "Not found")
Scala IO == Java + Commons IO vallines = Source.fromFile("d:scalaMobyDick.txt").getLines; valwithNumbers = lines.foldLeft(List(""))((l,s) => (s.length+" "+s)::l) println(withNumbers.mkString("")) withNumbers.foreach(println) withNumbers.filter(!_.startsWith("0")).map(_.toUpperCase). sort(_.length < _.length).foreach(println)
Scala DI - Cake Pattern traitPersonService { deffindByAge(age: Int): Person }   traitPersonServiceImplextendsPersonService { deffindByAge(age: Int): Person = new Person("", 12)  }     traitPersonDAO { defgetAll(): Seq[Person] }   traitPersonDAOImplextendsPersonDAO { defgetAll(): Seq[Person] = List(new Person("", 12)) }
Scala DI - Cake Pattern traitDirectory { 	self: PersonServicewithPersonDAO => }   classDirectoryComponentextends Directory withPersonServiceImplwithPersonDAOImpl { }
Guice Minimize mutability Avoid static state @Nullable

Contenu connexe

Tendances

JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
José Paumard
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Tendances (20)

JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
All about scala
All about scalaAll about scala
All about scala
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Java 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven editionJava 8 Streams & Collectors : the Leuven edition
Java 8 Streams & Collectors : the Leuven edition
 
Designing with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf IndiaDesigning with Groovy Traits - Gr8Conf India
Designing with Groovy Traits - Gr8Conf India
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 

Similaire à Scala == Effective Java

1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
wpgreenway
 
About java
About javaAbout java
About java
Jay Xu
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
NicholasflqStewartl
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
akshpatil4
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
retronym
 

Similaire à Scala == Effective Java (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
Features of Kotlin I find exciting
Features of Kotlin I find excitingFeatures of Kotlin I find exciting
Features of Kotlin I find exciting
 
About java
About javaAbout java
About java
 
Having a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdfHaving a problem figuring out where my errors are- The code is not run.pdf
Having a problem figuring out where my errors are- The code is not run.pdf
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
can do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdfcan do this in java please thanks in advance The code that y.pdf
can do this in java please thanks in advance The code that y.pdf
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Java 8 Examples
Java 8 ExamplesJava 8 Examples
Java 8 Examples
 
Elegant objects
Elegant objectsElegant objects
Elegant objects
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
5 Bullets to Scala Adoption
5 Bullets to Scala Adoption5 Bullets to Scala Adoption
5 Bullets to Scala Adoption
 
C# 3.5 Features
C# 3.5 FeaturesC# 3.5 Features
C# 3.5 Features
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 

Plus de Scalac

Plus de Scalac (14)

Applicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaApplicative functors by Łukasz Marchewka
Applicative functors by Łukasz Marchewka
 
AWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccAWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka Scalacc
 
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
 
React Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacReact Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv Scalac
 
Introduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacIntroduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski Scalac
 
ZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół ScalacZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół Scalac
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacHow to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
 
Do you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacDo you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych Scalac
 
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacCan we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
 
How to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńHow to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej Greń
 
ActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej Kopeć
 
Liftweb
LiftwebLiftweb
Liftweb
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Dernier (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Scala == Effective Java

  • 1. Clean Code Scala Scala == Effective Java ?
  • 2.
  • 3.
  • 4.
  • 5. „Leave camp cleaner than you found it.” Uncle Bob
  • 6.
  • 7. Why do we write bad code ??? Rush (duck tape programmer) Laziness Careless We don’t know how good code looks like Lack of resources We like to do new things (create)
  • 8. „Its harder to read the code than to write it” Joel Spolsky
  • 9. How to improve work quality ? Dont give developers money rewardsbigger reward == worse performance Let them work on what they like and how they like (Google, Atlassian, Facebook) Allow and encourage self improvement
  • 10. Java dev libraries Google Guava Apache Commons Spring Guice Scala !
  • 11. Why Scala ? More concise More powerfull Fun! Fast Becoming popular !
  • 12. Who uses Scala already
  • 13. Class Parameters - Java publicclass Person { private String name; privateintage; publicPerson(String name, int age) { this.name = name; this.age = age; } public String getName() { returnname; } publicvoid setName(String name) { this.name = name; } publicint getAge() { returnage; } publicvoid setAge(int age) { this.age = age; } }
  • 14. Class Parameters - Scala classPerson(var name: String, var age: Int)
  • 15. publicclass Person { private String name; privateintage; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { returnname; } publicvoidsetName(String name) { this.name = name; } publicintgetAge() { returnage; } publicvoidsetAge(int age) { this.age = age; } @Override public String toString() { returnString.format("Person: %s age: %s", name, age); } @Override publicinthashCode() { inthashCode = 0; for(char c: name.toCharArray()) { hashCode += c; } return 11 * hashCode + age; } @Override publicboolean equals(Object other) { if(other == null) returnfalse; if(other instanceof Person) { Person person = (Person)other; returnperson.name.equals(name) && person.age == age; } returnfalse; }
  • 16. Scala case class caseclass Person(name: String, age: Int) Dostajemy za darmo: equals(), hashCode() oraz toString() oraz niezmienną klasę (immutable).
  • 17. To equal or not to equal ?   Person p = new Person("Jan Kowalski", 30); Set<Person> set = new HashSet<Person>(); set.add(p); System.out.println(set.contains(p)); // true p.setAge(p.getAge()+1); System.out.println(set.contains(p)); // false ... WTF ???
  • 18. To equal or not to equal ? Iterator<Person> it = set.iterator(); booleancontainedP = false; while (it.hasNext()) { Person nextP = it.next(); if (nextP.equals(p)) { containedP = true; break; } } System.out.println(containedP); // true // ... ???
  • 19.
  • 20. Java – working with Person Object x = new Person("Bill Clinton", 64); if(x instanceof Person) { Person p = (Person)x; System.out.println(„Person name: "+p.getName()); } else { System.out.println("Not a person"); } x = "Lukasz Kuczera"; if(x instanceof Person) { Person p = (Person)x; System.out.println("hello "+p.getName()); } elseif(x instanceof String) { String s = (String)x; if(s.equals("Bill Clinton")) System.out.println("Hello Bill"); else System.out.println("hello: "+s); } else System.out.println("err, ???");
  • 21. Scala – Pattern Matching var x: Any = Person("Lukasz", 28); x match { case Person(name, age) => println("Person name: "+name); case _ => println("Not a person") } x = "Lukasz Kuczera" x match { case Person(name, age) => println("Person name: "+name) case"Bill Clinton" => println("hello Bill") case s: String => println("hello "+s) case _ => "err, ???" } Person name: Lukasz hello Lukasz Kuczera
  • 22. Parameter validation publicclass Person { private String name; privateintage; publicPerson(String name, int age) { if(name == null) { thrownew NullPointerException(); } if(age < 0) { thrownew IllegalArgumentException("Age < 0") } this.name = name; this.age = age; }
  • 23. Parameter validation caseclass Person(name: String, age: Int) { // @elidable(ASSERTION)assert(age > 0, "Age < 0")// by name parameter }
  • 24. Working with arrays Java publicclass Partition { Person[] all; Person[] adults; Person[] minors; { ArrayList<Person> minorsList = new ArrayList<Person>(); ArrayList<Person> adultsList = new ArrayList<Person>(); for(int i=0; i<all.length; i++ ) { (all[i].age<18 ? adultsList: minorsList).add(all[i]); } minors = (Person[]) minorsList.toArray(); adults = (Person[]) adultsList.toArray(); } }
  • 25. Working with arrays Scala val all: Array[Person] val (minors, adults) = all.partition(_.age<18)
  • 26. Null’s – Java Map<String, String> capitals = new HashMap<String, String>(); capitals.put("Poland", "Warsaw"); System.out.println(capitals.get("Polska").trim()); Exception in thread "main" java.lang.NullPointerException
  • 27. Null’s - Scala val capitals = Map("Poland" -> "Warsaw"); val capitalOption: Option[String] = capitals.get("Polska") capitalOption match { case Some(value) => println(value) case None => println("Not found") case _ => } if(capitalOption.isDefined) println(capitalOption.get) println(capitalOption getOrElse "Not found")
  • 28. Scala IO == Java + Commons IO vallines = Source.fromFile("d:scalaMobyDick.txt").getLines; valwithNumbers = lines.foldLeft(List(""))((l,s) => (s.length+" "+s)::l) println(withNumbers.mkString("")) withNumbers.foreach(println) withNumbers.filter(!_.startsWith("0")).map(_.toUpperCase). sort(_.length < _.length).foreach(println)
  • 29. Scala DI - Cake Pattern traitPersonService { deffindByAge(age: Int): Person }   traitPersonServiceImplextendsPersonService { deffindByAge(age: Int): Person = new Person("", 12) }     traitPersonDAO { defgetAll(): Seq[Person] }   traitPersonDAOImplextendsPersonDAO { defgetAll(): Seq[Person] = List(new Person("", 12)) }
  • 30. Scala DI - Cake Pattern traitDirectory { self: PersonServicewithPersonDAO => }   classDirectoryComponentextends Directory withPersonServiceImplwithPersonDAOImpl { }
  • 31. Guice Minimize mutability Avoid static state @Nullable