Scala简明教程(1)
Scala简明教程
目录
变量声明
函数
包package
数据结构
字符串
控制流程
模式匹配
面向对象
泛型
注解
Implicit
空对象Nil,Null,null,Unit,Nothing,None
Scala是一门多范式(multi-paradigm)的编程语言。
Scala源代码被编译成Java字节码,所以它可以运行于JVM之上,并可以调用现有的Java类库。
洛桑联邦理工学院的Martin Odersky于2001年基于Funnel的工作开始设计Scala。Funnel是把函数式编程思想和佩特里网相结合的一种编程语言。Odersky先前的工作是Generic Java和javac。Java平台的Scala于2003年底/2004年初发布。该语言第二个版本,v2.0,发布于2006年3月。
Scala是面向对象的,比Java更彻底
一切皆为对象, 数值,函数都是对象
强大的静态类型系统 algebraic data types, covariance and contravariance, higher-order types, anonymous types, generic classes, upper and lower type bounds, inner classes and abstract types as object members, compound types, explicitly typed self references , views and polymorphic methods
其它Java不支持的功能:
operator overloading, optional parameters, named parameters, raw strings, and no checked exceptions
2009年4月,Twitter宣布他们已经把大部分后端程序从Ruby迁移到Scala,其余部分也打算要迁移。这里有一篇文章解释Twitter为什么使用Scala编程语言。
Engineer-to-Engineer Series Programming Languages Programming Languages Scala Talks
Coursera把Scala作为服务器语言使用。Why we love Scala at Coursera
一些Scala学习资料:
Scala documentation
Learning Scala
Effective Scala
Scala School
Scala cheatsheets
大数据生态圈中的Kafka和Spark都是由Scala开发的,这也是我为什么学习Scala的原因之一。
作为一个Java程序员,我觉得Scala的语法和类C语言如Java,C#等很不一样, 很多语法的技巧在里面。 基于此,我特地整理了这篇文章。 简单扼要的介绍Scala语言的知识点,尤其是和Java不太一样的地方
$变量声明
- var x = 5
- var x:Double = 5
- val y = 7
var声明变量, val声明常量, 类型可省略, Scala可以推断出数据类型
函数:
- def f(x: Int) = { x*x }
- def f(x: Any): Unit = println(x)
- reply()
- reply
- names foreach (n => println(n))
- names mkString ","
- optStr getOrElse "<empty>"
一个参数时可以使用infix写法
infix操作符可以定义如下:
- class MyBool(x: Boolean) {
- def and(that: MyBool): MyBool = if (x) that else this
- def or(that: MyBool): MyBool = if (x) this else that
- def negate: MyBool = new MyBool(!x)
-
- def not(x: MyBool) = x negate; // semicolon required here
- def xor(x: MyBool, y: MyBool) = (x or y) and not(x and y)
- }
-
- //更多例子
- 5.+(3); 5 + 3
- (1 to 5) map (_*2)
- def f(x: R)
- def f(x: => R)
匿名函数(lambda表达式)
- (x:R) => x*x
=>可以由 ⇒ 字符替代(\u21D2),同样 <-和 ->也可以由单个的字符取代: ← 和 →
- (1 to 5).map(_*2)
- (1 to 5).reduceLeft( _+_ )
- (1 to 5).map(2*)
- 等价
- (1 to 5).map(2* _)
- (1 to 5).map { val x=_*2; println(x); x }
- (1 to 5) filter {_%2 == 0} map {_*2}
- def compose(g:R=>R, h:R=>R) = (x:R) => g(h(x))
- val f = compose({_*2}, {_-1})
- val zscore = (mean:R, sd:R) => (x:R) => (x-mean)/sd //currying, obvious syntax.
- def zscore(mean:R, sd:R) = (x:R) => (x-mean)/sd //currying, obvious syntax
- def zscore(mean:R, sd:R)(x:R) = (x-mean)/sd //currying, 语法糖,也叫参数分组. 但是必须按照下面的语法调用:
- val normer = zscore(7, 0.4)_ //需要尾部的下划线,仅限于上面一行的语法糖
- def sum(args: Int*) = args.reduceLeft(_+_)