an introduction to scala
DESCRIPTION
A simple introduction of major features of scalaTRANSCRIPT
An Introduction to Scala
Why Scala• JVM Language + Static Typed Language
• Concise
• Design for FP + OO
• Built-in Actor model for better concurrency
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”)
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(“,”)
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)
}
Concise• Tuple
◦ Scaladef getKV(s: String) = {val secs = s.split(‘=‘)(secs(0), if (secs.size > 1) secs(1) else “”)
}
Concise• Customized Operators
◦ Scala:◦ var list = List(1, 2, 3, 4)◦ 0 :: list◦ list :+ 5◦ list ++ List(6, 7, 8)◦ (list :\ 0)(_ + _)
Concise• Omitted dot methods
◦ scala:◦ for (i <- 1 to 10) println(i)◦ for (i <- 1 until 10) println(i)
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
Object Orientation• object & class
◦ Scala:object StringUtils {
def foo() = println(“do something“)
}
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 + ")”}
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
Traits• How to reuse code pieces and combine them into
a single class (multi-interface implementation?, AOP?)
• This is where mixin comes
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” }
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)
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”)
}
Functional Programming• FP on recursion
◦ Scaladef factorial(i: BigInt): BigInt = i match {
case _ if i == 1 => icase _ => i * factorial(i – 1)
}
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◦ …
Functional Programming• FP on collection
◦ Scala(1 to 10000) reduceLeft(_ + _)(1 to 10000) reduceRight(_ + _)
Functional Programming• FP on collection
◦ Scalaval state2Capital = Map(
“Alabama” -> “Montgomery”,“Alaska” -> “Juneau”,“Wyoming” -> “Cheyenne”)
state2Capital filter { kv => kv._1 startsWith “A” }
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”)}
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”)
Functional Programming• Curry
◦ Scala:◦ def foo(s1: String)(s2: String) = s1 + s2◦ foo(“Hello”)(“World”)
Actor• What is Actor
A
A
A
A
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
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”) } }}
Actor• Actor classclass MyActor extends Actor {def act() {//…
}}val myactor = new MyActormyactor start
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) } }}
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
Other features not mentioned• Parallel collections
• Case Class
• Generic
• Explicitly Typed Self References
• Named Parameters
• Option
• View
• Implicit Type Conversion
• Future
• …
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
Q&A