This document introduces Scala and its key features. Scala is a JVM language that combines object-oriented and functional programming. It allows for concise code through features like type inference, method declaration simplification, and pattern matching. Scala supports both object-oriented concepts like classes and traits as well as functional programming with immutable data structures and higher-order functions. It also builds in support for concurrency through its Actor model. In summary, Scala aims to make code more concise while enabling functional and concurrent programming on the JVM.
2. Why Scala
• JVM Language + Static Typed Language
• Concise
• Design for FP + OO
• Built-in Actor model for better concurrency
3. 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”);
◦ Scala
var m = HashMap(“one”->1, “two”->2)
var v = m(“One”)
7. Concise
• Customized Operators
◦ Scala:
◦ var list = List(1, 2, 3, 4)
◦ 0 :: list
◦ list :+ 5
◦ list ++ List(6, 7, 8)
◦ (list : 0)(_ + _)
8. Concise
• Omitted dot methods
◦ scala:
◦ for (i <- 1 to 10) println(i)
◦ for (i <- 1 until 10) println(i)
9. 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
11. 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 + ")”
}
12. 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
13. Traits
• How to reuse code pieces and combine them into
a single class (multi-interface implementation?,
AOP?)
• This is where mixin comes
14. 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” }
15. 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)
17. Functional Programming
• FP on recursion
◦ Scala
def factorial(i: BigInt): BigInt = i match {
case _ if i == 1 => i
case _ => i * factorial(i – 1)
}
21. Functional Programming
• FP on Thread
◦ Java:
Thread t = new Thread {
@Override
public 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”)}
22. 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”)
25. 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
mailbox
Matcher
&
handlers
Immutable msg
26. Actor
• Try Actor
import scala.actors.Actor
import 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”)
}
}
}
27. Actor
• Actor class
class MyActor extends Actor {
def act() {
//…
}
}
val myactor = new MyActor
myactor start
28. 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
}
}
}a
ccumulator ! 1
accumulator ! 2
accumulator ! 3
receiveWithin(1000) {
case result => println("Total is " + result)
}
}
}
29. 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
30. Other features not mentioned
• Parallel collections
• Case Class
• Generic
• Explicitly Typed Self References
• Named Parameters
• Option
• View
• Implicit Type Conversion
• Future
• …
31. 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