hello scala
DESCRIPTION
Introduction to Scala.TRANSCRIPT
Hello ScalaJINLIANG OU
2014 04
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
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
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
Scala Is Used By Companies:
◦ Twitter, LinkedIn, Siemens, Amazon, SONY, Foursquare, …
Libraries and Frameworks◦ Akka, Kafka, Finagle, Spark, Play! Lift, …
Scala 是简洁的 Java Type less, do more.
Less code, fewer bugs.
一些东西是可以省略的 表达式后的分号
◦ 基本都是不需要的 ( 除非你想一行写多条,不建议 )
return 关键字◦ 大部分可以省略, 除了少数情况必须从函数中间返回
没有参数的函数调用和声明◦ a.toString => a.toString()
方法调用中间的 . ◦ 在某些 DSL 的场合◦ nameList foreach println => nameList.foreach(n => println(n))
类型 ( 见下页 )
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”
简洁的表达 简化的类定义:
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) // trueval even = list.filter(_ % 2 ==0) // List(2, 4, 6)
转换val id = “12345”.toInt
val list = Array(“a”, “b”, “c”).toList
val set = list.toSet
其它有用的特性 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 """
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
Scala is Object Oriented It’s PURE OO
一切都是对象 , Scala 是面向对象的,没有 Java 中的所谓静态等非对象的东西( 想想 Java 有哪些不是 pure OO 的?基本类型,静态类?)◦ 1 + 2 ◦ 1.+(2)
OO 有哪些特性?哪些原则?
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()
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
◦ 函数作为参数,返回值都可以
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)
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() )
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”)
其他高级货o 并发, actor, Akka, 并发 collections
o Generic, variance, co-variance
o Implicit conversions
o Partially applied functions
o Currying
o For comprehensions
o Macro
o…
使用 ScalaIDE:◦ Eclipse (http://scala-ide.org, 官方支持, 很好用 ) ◦ IntelliJ IDEA (with the Scala plugin, JetBrains 官方插件 , 很好用 )◦ NetBeans (with the Scala plugin, 没用过 )
Build Tool:◦ Sbt (simple build tool, Scala 项目默认都使用的 )◦ Maven (with plugin) 我在一些项目里使用这个,混合 Java + Scala ◦ Ant..
Test ◦ 可以使用 Junit◦ 也可以使用专门给 Scala 设计的 : specs, scala test …
Libraries and Frameworks◦ 找得到 Scala 的用 Scala 的,找不到就用 Java 的!◦ https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
缺点 编译速度
◦ 使用 IDE 的增量编译
二进制不兼容◦ 使用版本化
语法越来越复杂◦ 易上手,难精通◦ 开始不要使用高级功能◦ 应用开发和库开发需要使用的技能是不同的◦ 不要炫技
用的人少, 招聘难◦ 学吧 , 用 Scala 的人越来越多了。
学习 Scala 开始:
◦ http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html ◦ http://twitter.github.io/scala_school/ (http://twitter.github.io/scala_school/zh_cn/index.html )
全面学习◦ Programming in Scala
Effective Scala◦ http://twitter.github.io/effectivescala/index.html