Download - Scala taxonomy

Transcript
Page 1: Scala taxonomy

Scala taxonomy explainedfrom Java programmer

[email protected]

Page 2: Scala taxonomy

Agenda● OO Features● Pattern matching● Functional Programming● Actors● Futures● Implicits

Page 3: Scala taxonomy

Data Transfer Objetsclass Person {

private String firstName;

String getFirstName() {

return firstName;

}

void setFirstName(String aFirstName) {

this.firstName = aFirstName;

}

}

Page 4: Scala taxonomy

toString@Override

public String toString() {

return "Person{" +

"firstName='" + firstName + '\'' +

", lastName='" + lastName + '\'' +

'}';

}

Page 5: Scala taxonomy

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

}

Page 6: Scala taxonomy

hashCode @Override public int hashCode() { int result = firstName.hashCode(); result = 31 * result + lastName.hashCode(); return result; }

Page 7: Scala taxonomy

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;

}

Page 8: Scala taxonomy

Case Classescase class Person(firstName: String =

"Bill", lastName :String = "Gates")

val me = Person(lastName = "Crosby")

● Immutable● toString, equals, hashCode● person.copy(lastName="Malkin")

Page 9: Scala taxonomy

Laziness in JavaInteger cached = null;

Integer getExpensiveComputation() {

if (null == cached) {

cached = doCount();

}

return cached;

}

Page 10: Scala taxonomy

Lazy Definitionlazy val count = doCount()

Page 11: Scala taxonomy

Importsimport 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") ) }}

Page 12: Scala taxonomy

Java: Singletonspublic class Singleton {

private Singleton INSTANCE = null;

private Singleton() {}

public Singleton getInstance() {

if (null == INSTANCE) {

INSTANCE = new Singleton()

}

}

Page 13: Scala taxonomy

Objectsclass 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"

}

Page 14: Scala taxonomy

Pattern matchingIn Java:

Switch statements with String cases have been implemented in Java SE 7, at least 16 years after they were first requested.

Page 15: Scala taxonomy

Pattern matchingobject 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)

}

}

Page 16: Scala taxonomy

scala.annotation.switch(ch: @switch) match {

case 'a' if eof => println("a with oef")

case 'b' => println("b")

case 'c' => println("c")

}

Page 17: Scala taxonomy

Functional programming

Page 18: Scala taxonomy

ImmutabilityJava

String, BigDecimal

Scalaval immutable = 1var mutable = 2mutable = 3

Page 19: Scala taxonomy

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

Page 20: Scala taxonomy

Higher order functionsobject 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

}

Page 21: Scala taxonomy

Parallel collectionobject 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

}

Page 22: Scala taxonomy

Curryingobject 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

}

Page 23: Scala taxonomy

Partial functionsval 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)

Page 24: Scala taxonomy

Actors

Page 25: Scala taxonomy

Futuresimport 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

}

Page 26: Scala taxonomy

Implicit conversionsJava:

String.valueOf(int i), Integer.parseInt(String s)

Scala:(1 to 4).foreach(println)

Page 27: Scala taxonomy

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)

}

Page 28: Scala taxonomy

To be continued...


Top Related