Scala Intro

Post on 14-Jul-2015

148 views 0 download

transcript

Scalable Language

JVM

Scala Conventions

Return is almost optional ; is optional

No args functions doesn’t need ()

def sum(a: Int, b: Int) = a + b def sum(a: Int, b: Int) = {

println(a)

println(b)

a+b

}

def count() = {...}

val cnt = list.count

Type Inference

Scala is strongly typed Type is inferred by scala

val a: Int = 1 def funz(a: Int) = a*10.0

def funz2(a: Int):Double = a*10.0

Value vs Variable

A value is immutable A variable is mutable

scala val ~= java final attribute

val a = 1

a = 2 // error: reassignment to val

var a = 1

a = 2 // ok

Object Oriented

Classes

Constructor is class body itself! Costructors override

class Person(name:String) {

var age = 0

println(name)

}

class Person(name:String) {

var age = 0

def this(name:String, anAge:Int) {

this(name)

age = anAge

}

}

Case Classes

Equals() and hashcode() are already implemented!!

case class Color(name:String, code: Int)

val c = Color("red", 34567)

Embedded singleton patternScala hasn't static

because Scala is object oriented…. allows you define object

Object and class work togheterobject Obj {

def doSomething() = println

}

Obj.doSomething()class Color(name:String)

object Color { // this is the singleton

private val colors = Map(

"red" -> new Color("red"),

"green" -> new Color("green"),

"blue" -> new Color("blue"))

def mk(name:String) = colors(name)

}

TraitsSimilar to interfaces, but much more powerful!

trait Equal {

def isEqual(x: Any): Boolean //Scala allows traits to be partially implemented

def isNotEqual(x: Any): Boolean = !isEqual(x)

}

class Point(xc: Int, yc: Int) extends Equal {

val x = xc

val y = yc

def isEqual(obj: Any) = obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x

}

Multiple InheritanceTrait rules

trait Swimming { def swim() = println("I'm swimming") }

abstract class Bird { def fly() = println("I'm flying") }

class Bird1 extends Bird

class Bird2 extends Bird with Swimming

new Bird1().fly() // I'm flying

new Bird2().swim() //I'm swimming

(new Bird1() with Swimming).swim() //composable objects at runtime

Functional

First class function

def f1(x: Int) = x

def f2(x: Int) = x * 2

def g(f:Int=>Int, x:Int) = f(x) + 1

g(f1, 3) // f1(3) + 1 → 4

g(f2, 3) // f2(3) + 1 → 7

Pattern Matching

can match int, string, List, case class!

Match is a function too

case class Color(name: String, code: String)

val obj : Any = _

obj match {

case "string" => println("obj String")

case a: Int => println("obj is Int with value: "+a)

case l: List[_] => println("obj is a List")

case Color(name, code) => println("obj is the color: "+name)

case "string" :: item :: other => println("")

case _ => println("")

}

Scala vs Java

def products = orders.flatMap(_.products)

.filter(_.category == category)

val list = List(1,2,3)

public List<Product> getProducts() {

List<Product> products = new ArrayList<Product>();

for(Order order : orders) {

for(Product product : order.getProducts()) {

if(category.equals(product.getCategory())){

products.add(product);

}

}

}

return products;

}

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(1);

list.add(2);

list.add(3);

Scala XML

val foo = <foo>

<bar type="greet">hi</bar>

<bar type="count">1</bar>

<bar type="color">yellow</bar>

</foo>

(foo \ "bar").map(_ \ "@type")

Enterprise Ready

Scala JS

Scala.js compiles Scala code to JavaScript, allowing you to

write your web application entirely in Scala!

Jquery , AngularJS, NodeJS , etc... are already integrated!

Scalable

"Prefer vals, immutable objects,

and methods without side effects.

Reach for them first. Use vars,

mutable objects, and methods with

side effects when you have a

specific need and justification for

them."

Functional is statelessImmutable is stateless

shared or mutable states are scalability killers

Actors react to received messages by

executing a behavior function

Actors never share state and thus

never need to compete for locks for

access to shared data

Scala Features

Lazy val

Streams

String interpolation

Runtime code generation

Runtime reflection

Regex

Macros, quasiquotes, sequence comprehension, lambda, currying, tuple...etc.

lazy val funcVal = { println("executing"); 3 }

lazy val fibs = BigInt(0) #:: BigInt(1)

#:: Stream.empty

val str = s"the user ${username} has ${numOfTokens} tokens"

toolbox.eval(toolbox.parse("case class D(a: Int, b: Int)"))

def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]

val theType = getTypeTag(List(1,2,3)).tpe

val pattern = "(S|s)cala".r

pattern findFirstIn "Scala is Scalable and cool"

Any questions ?