Scala taxonomy

1,173 views

Published on

Scala terms explained for Java developer, immutability, implicits, pattern matching, futures

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,173
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
13
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Scala taxonomy

  1. 1. Scala taxonomy explainedfrom Java programmerRadim.Pavlicek@gmail.com
  2. 2. Agenda● OO Features● Pattern matching● Functional Programming● Actors● Futures● Implicits
  3. 3. Data Transfer Objetsclass Person {private String firstName;String getFirstName() {return firstName;}void setFirstName(String aFirstName) {this.firstName = aFirstName;}}
  4. 4. toString@Overridepublic String toString() {return "Person{" +"firstName=" + firstName + +", lastName=" + lastName + +};}
  5. 5. equals@Overridepublic 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. 6. hashCode@Overridepublic int hashCode() {int result = firstName.hashCode();result = 31 * result + lastName.hashCode();return result;}
  7. 7. Builderstatic 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. 8. Case Classescase class Person(firstName: String ="Bill", lastName :String = "Gates")val me = Person(lastName = "Crosby")● Immutable● toString, equals, hashCode● person.copy(lastName="Malkin")
  9. 9. Laziness in JavaInteger cached = null;Integer getExpensiveComputation() {if (null == cached) {cached = doCount();}return cached;}
  10. 10. Lazy Definitionlazy val count = doCount()
  11. 11. Importsimport scala.collection.immutable.Mapobject 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. 12. Java: Singletonspublic class Singleton {private Singleton INSTANCE = null;private Singleton() {}public Singleton getInstance() {if (null == INSTANCE) {INSTANCE = new Singleton()}}
  13. 13. Objectsclass CompanionObjects(val id: Long, valdescription: String = "")object CompanionObjects{def zero = new CompanionObjects(id = 0,description = "zero")def apply(id:Int, description:String)= newCompanionObjets(id,description)def one = CompanionObjets(1, "one")val errorMessage = "ID should be positive"}
  14. 14. Pattern matchingIn Java:Switch statements with String cases havebeen implemented in Java SE 7, at least 16years after they were first requested.
  15. 15. Pattern matchingobject Matching extends App {val name :AnyRef= ...name match {case "Radim" => println("me")case "crosby" | "sidney" => println("NHL")case Seq("sidney", _) => println("sidney withsomeone")case Seq("sidney", _*) => println("sidney with group")case x: Int if x < 0 => println("negative number")case y => println("Unknown " + y)}}
  16. 16. scala.annotation.switch(ch: @switch) match {case a if eof => println("a with oef")case b => println("b")case c => println("c")}
  17. 17. Functional programming
  18. 18. ImmutabilityJavaString, BigDecimalScalaval immutable = 1var mutable = 2mutable = 3
  19. 19. Immutability cont.val n = "123".reverseval m = n.reverseprintln(n, m) // 321, 123val o = new StringBuffer("123").reverse()val p = o.reverse()println(o, p) // 123, 123
  20. 20. Higher order functionsobject Collections extends App{val c = 4 to 8val s: IndexedSeq[String] = c map(_+"th")s map (_.toUpperCase)println(s) //4th, 5th, 6th, 7th, 8th}
  21. 21. Parallel collectionobject Parralel extends App{def time[R](block: => R): R = {val t0 = System.nanoTime()val result = block // call-by-nameval t1 = System.nanoTime()println("Elapsed time: " + (t1 - t0)/1000000 + " ms")result}val c = 1 to 10000000time { c map (_ + 1) } //4935 mstime { c.par map (_ + 1) } //3723 ms}
  22. 22. Curryingobject Curry extends App{def product(i: Int)(j: Int) = i * jdef times2 = product(2)_def times3 = product(3)_println(times2 (4)) //8println(times3 (4)) //12}
  23. 23. Partial functionsval sample = 1 to 10val isEven: PartialFunction[Int, String] ={case x if x % 2 == 0 => x+" is even"}// the method collect can use isDefinedAtto select which members to collectval evenNumbers = sample collect isEvenprintln(evenNumbers)
  24. 24. Actors
  25. 25. Futuresimport ExecutionContext.Implicits.globalobject Futures extends App {@volatile var totalA = 0val text = Future {Thread.sleep(1000); val a = "a" * 16}text onSuccess {case txt => totalA += txt.count(_ == a)}println(totalA) // 0Thread.sleep(1000); println(totalA) //0Thread.sleep(1000); println(totalA) //16}
  26. 26. Implicit conversionsJava:String.valueOf(int i),Integer.parseInt(String s)Scala:(1 to 4).foreach(println)
  27. 27. Implicit parametersobject 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)
  28. 28. To be continued...

×