Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
An Introduction to 
Scala 
jiankuan@yahoo-inc.com
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”); 
◦ Scala 
var 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 
◦ Scala 
def 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 
◦ Scala 
def factorial(i: BigInt): BigInt = i match { 
case _ if i == 1 => i 
case _ => i * factorial(i – 1) 
}
Functional Programming 
• FP on collection 
◦ Scala 
List(1, 2, 3, 4, 5, 6).map(x=>x * 2) 
List(1, 2, 3, 4, 5, 6) map { _ * 2 } 
def toDouble(x:Int) = x * 2 
List(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 
◦ Scala 
val 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 { 
@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”)}
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 
mailbox 
Matcher 
& 
handlers 
Immutable msg
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”) 
} 
} 
}
Actor 
• Actor class 
class MyActor extends Actor { 
def act() { 
//… 
} 
} 
val myactor = new MyActor 
myactor 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 
} 
} 
}a 
ccumulator ! 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

More Related Content

An introduction to scala

  • 1. An Introduction to Scala jiankuan@yahoo-inc.com
  • 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”)
  • 4. 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(“,”)
  • 5. 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) }
  • 6. Concise • Tuple ◦ Scala def getKV(s: String) = { val secs = s.split(‘=‘) (secs(0), if (secs.size > 1) secs(1) else “”) }
  • 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
  • 10. Object Orientation • object & class ◦ Scala: object StringUtils { def foo() = println(“do something“) }
  • 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)
  • 16. 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”) }
  • 17. Functional Programming • FP on recursion ◦ Scala def factorial(i: BigInt): BigInt = i match { case _ if i == 1 => i case _ => i * factorial(i – 1) }
  • 18. Functional Programming • FP on collection ◦ Scala List(1, 2, 3, 4, 5, 6).map(x=>x * 2) List(1, 2, 3, 4, 5, 6) map { _ * 2 } def toDouble(x:Int) = x * 2 List(1, 2, 3, 4, 5, 6) map toDouble ◦ FP functions ◦ map ◦ reduce ◦ foldleft/foldright ◦ groupby ◦ filter ◦ max ◦ min ◦ foreach ◦ …
  • 19. Functional Programming • FP on collection ◦ Scala (1 to 10000) reduceLeft(_ + _) (1 to 10000) reduceRight(_ + _)
  • 20. Functional Programming • FP on collection ◦ Scala val state2Capital = Map( “Alabama” -> “Montgomery”, “Alaska” -> “Juneau”, “Wyoming” -> “Cheyenne”) state2Capital filter { kv => kv._1 startsWith “A” }
  • 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”)
  • 23. Functional Programming • Curry ◦ Scala: ◦ def foo(s1: String)(s2: String) = s1 + s2 ◦ foo(“Hello”)(“World”)
  • 24. Actor • What is Actor A A A A
  • 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
  • 32. Q&A

Editor's Notes

  1. ----- Meeting Notes (9/1/14 17:39) -----