an introduction to scala

32
An Introduction to Scala [email protected]

Upload: xing

Post on 04-Jun-2015

108 views

Category:

Technology


0 download

DESCRIPTION

A simple introduction of major features of scala

TRANSCRIPT

Page 1: An introduction to scala

An Introduction to Scala

[email protected]

Page 2: An introduction to scala

Why Scala• JVM Language + Static Typed Language

• Concise

• Design for FP + OO

• Built-in Actor model for better concurrency

Page 3: An introduction to scala

Concise• Type Inferal

◦ Java:HashMap<String, Int> m = new HashMap<String, Int>();m.put(“one”, 1);m.put(“two”, 2);int v = m.get(“one”);

◦ Scalavar m = HashMap(“one”->1, “two”->2)var v = m(“One”)

Page 4: An introduction to scala

Concise• Method Declaration

◦ Java:public String foo(String[] strs) {StringBuilder sb = new StringBuilder()for (String str: strs) {sb.append(str);

sb.append(“,”);}

if (sb.length() > 0) { sb.setLength(sb.length() – 1); }return sb.toString();

}

◦ Scala:◦ def foo(strings: String*):String = strings.mkString(“,”)

Page 5: An introduction to scala

Concise• Nested Function:

◦ Scala:def factorial(i: Int): Int = {

def fact(i: Int, product: Int): Int = {

if (i <= 1)

product

else

fact(i – 1, product)

}

fact(i, 1)

}

Page 6: An introduction to scala

Concise• Tuple

◦ Scaladef getKV(s: String) = {val secs = s.split(‘=‘)(secs(0), if (secs.size > 1) secs(1) else “”)

}

Page 7: An introduction to scala

Concise• Customized Operators

◦ Scala:◦ var list = List(1, 2, 3, 4)◦ 0 :: list◦ list :+ 5◦ list ++ List(6, 7, 8)◦ (list :\ 0)(_ + _)

Page 8: An introduction to scala

Concise• Omitted dot methods

◦ scala:◦ for (i <- 1 to 10) println(i)◦ for (i <- 1 until 10) println(i)

Page 9: An introduction to scala

Concise• Match

◦ Scala:def bet(n: Int) = {

n match {

case 5 => println(“Win”)

case x if x > 9 => println(“Not bad”)

case _ => println(“Try again”)

}◦ More

◦ string match◦ type match◦ guard match◦ tuple match◦ sequence match◦ regex match

Page 10: An introduction to scala

Object Orientation• object & class

◦ Scala:object StringUtils {

def foo() = println(“do something“)

}

Page 11: An introduction to scala

Object Orientation• Define a class

◦ Scala:class Point(xc: Int, yc: Int) { // default constructor def this(xc: Int) = this(xc, 0) private var x: Int = xc private var y: Int = yc def move(dx: Int, dy: Int) { x = x + dx y = y + dy } override def toString(): String = "(" + x + ", " + y + ")”}

Page 12: An introduction to scala

Object Orientation• Visibility

◦ private, public, protected◦ scoped

◦ private[this] – package private◦ private[T] – private but accessible to class T◦ private[package] – private but accessible to package

Page 13: An introduction to scala

Traits• How to reuse code pieces and combine them into

a single class (multi-interface implementation?, AOP?)

• This is where mixin comes

Page 14: An introduction to scala

Traits• Sample traits, just an interface which can contains

default implementation◦ Scala:trait Friendly { def greet() = “Hi” }

class Dog extends Friendly { orverride def greet() = “Woof” }

Page 15: An introduction to scala

Traits• Combination when instance is created

◦ Scala:trait Friendly { def greet() = “Hi” }trait ExclamatoryFriendly extends Friendly { override def greet() = super.greet() + “!” }class Dog extends Friendly {override def greet() = “I’m a dog”}val d1 = new Dog; println(d1.greet)val d2 = new Dog with ExclamatoryFriendly; println(d2.greet)

Page 16: An introduction to scala

Traits• Implements AOP

◦ Scala:trait Clickable { def click}

trait LogClickable extends Clickable { abstract override def click = {

println(“before log”); super.click; println(“click is logged”)}}

trait CallbackClickable extends Clickable {

abstract override def click = {

println(“before callback”);

super.click;

println(“callback has been invoked for click”)

}

}

class Button extends Clickable {

override def click = println(“button is clicked”)

}

Page 17: An introduction to scala

Functional Programming• FP on recursion

◦ Scaladef factorial(i: BigInt): BigInt = i match {

case _ if i == 1 => icase _ => i * factorial(i – 1)

}

Page 18: An introduction to scala

Functional Programming• FP on collection

◦ ScalaList(1, 2, 3, 4, 5, 6).map(x=>x * 2)List(1, 2, 3, 4, 5, 6) map { _ * 2 }def toDouble(x:Int) = x * 2List(1, 2, 3, 4, 5, 6) map toDouble

◦ FP functions◦ map◦ reduce◦ foldleft/foldright◦ groupby◦ filter◦ max◦ min◦ foreach◦ …

Page 19: An introduction to scala

Functional Programming• FP on collection

◦ Scala(1 to 10000) reduceLeft(_ + _)(1 to 10000) reduceRight(_ + _)

Page 20: An introduction to scala

Functional Programming• FP on collection

◦ Scalaval state2Capital = Map(

“Alabama” -> “Montgomery”,“Alaska” -> “Juneau”,“Wyoming” -> “Cheyenne”)

state2Capital filter { kv => kv._1 startsWith “A” }

Page 21: An introduction to scala

Functional Programming• FP on Thread

◦ Java:Thread t = new Thread {@Overridepublic void run() {System.out.println(“This is a java thread”);

}}();t.start();

◦ Scala:val t = new Thread{println(“This is a one shot scala thread”)}

Page 22: An introduction to scala

Functional Programming• Partial Function

◦ Scala:def log(level: String, msg:String) = println(s”[${level}]:${msg}”)

val anotherLog = log _

anotherLog(“INFO”, “Everything is OK”)

val error = log(“ERROR”, _: String)

error(“Huston, we have a problem”)

Page 23: An introduction to scala

Functional Programming• Curry

◦ Scala:◦ def foo(s1: String)(s2: String) = s1 + s2◦ foo(“Hello”)(“World”)

Page 24: An introduction to scala

Actor• What is Actor

A

A

A

A

Page 25: An introduction to scala

Actor• Inside Actor

◦ Communicate by immutable msgs

◦ Can send msg sync or async◦ Handler can resp or not◦ Handler can create new

actors or send new msgs

Actor

mailboxMatcher

& handlers

Immutable msg

Page 26: An introduction to scala

Actor• Try Actorimport scala.actors.Actorimport scala.actors.Actor._val myActor = actor { loop { receive { case s: String => println(“I got a String, wow: “ + s) case List(_, _, 3, _) => println(“Amazing, a list with 3 as the 3rd element”) case i: Int => println(“Good, here is a number: “ + i) case _ => println(“Don’t know what you are talking about”) } }}

Page 27: An introduction to scala

Actor• Actor classclass MyActor extends Actor {def act() {//…

}}val myactor = new MyActormyactor start

Page 28: An introduction to scala

Actor• Send msgs

object Demo { def main(args: Array[String]): Unit = {    val caller = self    val accumulator = actor {     var continue = true     var sum = 0     loopWhile(continue) {         reactWithin(500) {           case number: Int => sum += number           case TIMEOUT =>             continue = false             caller ! sum         }       }     }     accumulator ! 1     accumulator ! 2     accumulator ! 3     receiveWithin(1000) {       case result => println("Total is " + result)     } }}

Page 29: An introduction to scala

Try Akka• Akka, a better implementation of actor

• Distributed together with Scala and used as default actor implementation since 2.10

• Go to talk with Jianying

Page 30: An introduction to scala

Other features not mentioned• Parallel collections

• Case Class

• Generic

• Explicitly Typed Self References

• Named Parameters

• Option

• View

• Implicit Type Conversion

• Future

• …

Page 31: An introduction to scala

Summary• Scala can

◦ Help you to shrink your code and make you concentrate on the business without performance penalty

◦ Let you use anything that you can use in Java or any other JVM languages

◦ Make your code easier to fit in running concurrently◦ Provide an opportunity to define a DSL

• But◦ Need great efforts to get used to FP + OO code style

Page 32: An introduction to scala

Q&A