This document introduces Scala and compares it to Java. It discusses Scala's features like being statically typed yet having type inference, being object-oriented and functional, and being concise. It provides examples of Scala code and how Scala can simplify tasks like parsing files, working with collections, pattern matching, and XML processing. It also discusses how Scala is used in industry, tools for using Scala, and resources for learning Scala.
2. The First Example
http://git.n.xiaomi.com/oujinliang/scala-intro
假设我们要解析这个文件,对符合条件的每一行构造一个对象(Xmq), 构造一个列表,对某两列排序,然后对这
个列表的每一个对象进行操作(print):
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/xmq.txt
Java Solution:
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/java/org/jinou/javasample/ParseXmqNodes.java
Scala Solution:
http://git.n.xiaomi.com/oujinliang/scala-intro/blob/master/src/main/scala/org/jinou/scalasample/ParseXmqNodes.scala
3. About Scala
Scalable Language 的缩写
By Martin Ordersky (Generic Java 作者,最初 javac 的参考实现的作者)
James Gosling (Creator of Java):
◦ "Which Programming Language would you use *now* on top of JVM, except Java?".
◦ The answer was surprisingly fast and very clear: - Scala.
James Strachan (Created Groovy in 2003):
◦ I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex
Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.
◦ http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html
4. About Scala (features)
oGeneral purpose Language
oJVM based (full inter-op with Java, community, libraries)
oFast
oStatically Typed (Type safe)
oObject Oriented
oFunctional
oConcurrency
oConcise and Expressive
oPowerful, highly Scalable,
oProductivity
5. Scala Is Used By
Companies:
◦ Twitter, LinkedIn, Siemens, Amazon, SONY, Foursquare, …
Libraries and Frameworks
◦ Akka, Kafka, Finagle, Spark, Play! Lift, …
8. Type Inference
类型推导, 静态语言写出动态语言的感觉. 在能推导出类型的时候,可以省略类型
值或变量的类型
◦ val sum = 1 + 2 + 3
◦ 和下面的等价,Compiler 推导出类型为 Int
◦ val sum : Int = 1 + 2 + 3
◦ var names = List(“Steve”, “Mike”, “Bob”)
◦ List[String]
◦ val map = Map(1234 -> Person(“Jim”, 18), 5678 -> Person(“Jack”, 22))
◦ Map[Int, Person]
函数的返回类型 (def 是函数定义的关键字)
◦ def getName = “myName”
◦ 等价于:
◦ def getName() : String = “myName”
9. 简洁的表达
简化的类定义:
class Xmq(chid:Int, start:Long, end:Long, host:String, port:Int, site:String) {
override def toString = “xxxx”
}
val xmq = new Xmq(1, 1, 10000, “localhost”, 7915, “site0”)
利用高价函数进行简化
val list = List(1, 2, 3, 4, 5, 6)
val hasTwo = list.exists(_ == 2) // true
val even = list.filter(_ % 2 ==0) // List(2, 4, 6)
转换
val id = “12345”.toInt
val list = Array(“a”, “b”, “c”).toList
val set = list.toSet
10. 其它有用的特性
Tuple:
◦ 有的时候你需要组合两个或三个对象,但创建一个类又太 heavy.
◦ val (host, port) = getHostAndPort(xxxx)
Default Parameter value, Named Parameter
Raw String:
◦ Java 中字符串转义,拼接太麻烦了,
◦ 可读性很重要
"""[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]""? (Scala)
Or
"[(d+),s*(d+),s*(d+),s*"(.+)",s*(d+),s*"(.+)".*]" (Java)
val usage = """Usage:
1. xxxx
2. yyyy
3. xxxx
"""
11. XML
case class Book(val name: String, val price: Int)
object XmlSample {
def main(args: Array[String]) {
val xml = getBooksXml("computer", 2, List(Book("C Language", 10), Book("Java Memory Model", 40)))
println(xml)
println(xml "@category") // get the attribute
}
def getBooksXml(category: String, version: Int, books: List[Book]): Node =
<books category={category} version={version.toString}> { books.map(getBookXml) } </books>
def getBookXml(book: Book) = <book name={book.name} price={book.price.toString} />
}
<books version="2" category="computer"> <book name="C Language" price="10"></book><book name="Java Memory Model" price="40"></book> </books>
computer
12. Scala is Object Oriented
It’s PURE OO
一切都是对象, Scala 是面向对象的,没有Java 中的所谓静态等非对象的东西
(想想 Java 有哪些不是 pure OO 的?基本类型,静态类?)
◦ 1 + 2
◦ 1.+(2)
OO 有哪些特性?哪些原则?
13. Class/Object/Trait
object vs. class
◦ class 和 Java 中的概念一样,用来创建对象的
◦ object is singleton !
◦ 忘记各种复杂的 singleton 的构造方式吧,忘记 double-checked locking
Trait
◦ Interface in Java, 可以有预定义的方法 (Java 8 ?)
◦ Mixin (解决Java 中无法多继承的问题)
object IdGenerator {
private val acc = new AtomicInteger(0)
def nextId() = acc.incrementAndGet
}
val newId = IdGenerator.nextId()
14. Scala is Functional
Function is first-class citizen
◦ 单独声明一个函数:
def foo(a: Int) = {
a * 2
}
foo(3)
◦ 函数作为变量
val plus2 = (x: Int) => x + 2
plus2(3) // 5
◦ 函数作为参数,返回值都可以
15. Higher Order Function
a higher-order function is a function that does at least one of the following:
◦ takes one or more functions as an input
◦ outputs a function
val plus2 = (x: Int) => x + 2
val nums = List(1,2,3,4)
// higher order functions
val double = nums.map(_*2) //
◦ or nums.map(n => n * 2) // List(2,4,6,8)
val allPlus2 = nums.map(plus2) // List(3,4,5,6)
val reduce = nums.reduce(_ + _) // 10
val result = nums.filter(_ > 2) // List(3,4)
16. Higher-order function example
def withClient[T](f: Client => T) = {
val client = getClient
try {
f(client)
} finally {
client.close
}
}
val i: Int = withClient( _.getIntValue() )
val s: String = withClient( _.getStringValue() )
17. Pattern Match
Java 的 switch/case 太弱了。
Scala 可以匹配 (基本类型,String, 正则表达式,List, case 对象… )
def what(any: Any) = any match {
case i: Int => "I'm int"
case s: String if s.startsWith("s") => "Starts with s "
case "hello" => "This is a hello"
case _ => "what ever "
}
what(123)
what(“hello”)
what(“scala”)
18. 其他高级货
o 并发, actor, Akka, 并发collections
o Generic, variance, co-variance
o Implicit conversions
o Partially applied functions
o Currying
o For comprehensions
o Macro
o…