[toc]
0 hello world
object Hello {
def main(args: Array[String]) = println("Hello world")
}
or
object Hello extends App {
println("Hello World")
}
1变量
- val 定义 immutable variable
- var 定义 mutable vraiable
- lazy val 赋值是不会计算值,调用才计算
可以不显示指定变量的类型,scala会自动进行类型推导
2 类型
scala类型系统以Any为根,分为AnyRef和AnyVal 两个分支体系,在AnyRef分支的最底层,有个Null类型的特殊类型,它被当作是所有AnyRef类型的子类型。更进一步在两个分支共同的最底层类型是Nothing类型,它被当作所有AnyRef和AnyVal类型的子类型。
2.1 umerical类型
- Byte 1字节
- Short 2
- Int 4
- Long 8
- Foat
- Double
高精度类型 a = 低精度类型 b (同c自动转换)
低精度类型 b = 高精度类型 a (error :type mismatch)
2.2 Boolen 类型
false
true
2.3 Char 类型
16 bit unsigned Unicode character. Range from U+0000 to U+FFFF
2.4 Unit 类型
it is not represented by any object in the underlying runtime system
A method with return type Unit is analogous to a Java method which is declared void.
val p=()
2.5 Null
Null类型只有一个唯一的值:null,可以被赋给所有的AnyRef类型变量
List(Null,Null,1)
2.6 Nothing
程序异常返回
2.7 String
val name =jin
s"my name is ${name}"
3 Block代码块
Block 也是一个表达式,其最终的求得的值是最后一个表达式的值
# 单行
{exp1;exp2}
{
exp1
exp2
}
4 函数
4.0 一等公民
- 函数作为实参传递给另一函数
- 函数作为返回值
- 把函数赋值为变量
- 把函数储存在数据结构里
4.0 .1函数类型
函数的类型格式为:A => B,表示一个接受A的参数,并返回B的参数
Int => String 是把整型函数映射为字符串的函数类型
4.0.2 高阶函数
用函数作为形参或者返回值的函数
// 参数是一个函数,这个函数有两个Int的参数,返回一个Int参数.
def operate(f:(Int, Int) =>Int) ={
f(4,4)
def add() = (x:Int, y:Int) => { x+ y}
}
4.1 定义
def functionName (param: Param Type):Reurn Type = {
//function body:expression
}
# 单行
def functionName (param: Param Type):Reurn Type = function body:expression
def hello(para:String):String={ "hello"+ para}
4.2 调用方式的不同
- call by value 调用时计算参数的值
def test(x:Int, y:Int) = x+y - call by name 调用时不计算参数的值
def test(x:=>Int y:=>Int Y) = x+y
def bar(x:Int,y:=>Int) = 1
def loop():Int = loop
bar(1,loop()) # 1
bar(loop(),1) # 死循环
疑问?
def loop():Int = loop
loop
为什么会死循环呢?
https://stackoverflow.com/questions/43561397/scala-def-loop-unit-loop-why-loop-forever
4.3 匿名函数
匿名函数的定义:
(形参列表) => { 函数体 }
(x:Int, y:Int) => { x+ y}
val add = (x:Int, y:Int) => { x+ y}
4.4 柯里化,偏函数
柯里化函数(Curried Function) 把具有多个参数的函数转化为一条函数链,每一个节点上是单一函数
def add(x:Int, y:Int) = x+y
def add(x:Int)(y:Inr) = x+y
def curriedAdd(a:Int)(b:Int) = a+b
curriedAdd(2)(2)
val addOne = curriedAdd(1)_
def curriedAdd1(a:Int, b:Int) = a+b
def curriedAdd(a:Int,b:Int) = a+b
def addTwo = curriedAdd( _:Int , 1:Int)
4.5 可变长度参数
参数:类型* 类似于Python的参数收集args,*kwargs
def capitalizeAll(args: String*) = {
args.map { arg =>
arg.capitalize
}
}
5 控制语句
5.1 if 表达式
if(logical) vala else valb
if( x == 10 ){
println("Value of X is 10"); }
else if( x == 20 ){
println("Value of X is 20"); }
else if( x == 30 ){
println("Value of X is 30"); }
else{ println("This is else statement"); }
5.2 for
for( a <- 1 to 10){
println( "Value of a: " + a );
// for loop execution with a range
for( a <- 1 until 10){
println( "Value of a: " + a ); }
- 多个参数
// for loop execution with a range
for( a <- 1 to 3; b <- 1 to 3){
println( "Value of a: " + a );
println( "Value of b: " + b );
}
- 过滤
val numList = List(1,2,3,4,5,6,7,8,9,10);
// for loop execution with multiple filters
for( a <- numList if a != 3; if a < 8 ){
println( "Value of a: " + a );
}
- 列表推导
var a = 0;
val numList = List(1,2,3,4,5,6,7,8,9,10);
var retVal = for{ a <- numList
if a != 3;
if a < 8;
s = a +1 }
yield s
5.3 while 和 do while
var a = 10;
// while loop execution
while( a < 20 ){
println( "Value of a: " + a );
a = a + 1;}
// do loop execution
do {
println( "Value of a: " + a );
a = a + 1;
}
while( a < 20 ) }
5.4 match表达式
val alice = new Person("Alice", 25)
val bob = new Person("Bob", 32)
val charlie = new Person("Charlie", 32)
for (person <- List(alice, bob, charlie)) {
person match {
case Person("Alice", 25) => println("Hi Alice!")
case Person("Bob", 32) => println("Hi Bob!")
case Person(name, age) => println(
"Age: " + age + " year, name: " + name + "?")
}
}
}
#这个类是特殊的用以比较的类
case class Person(name: String, age: Int)
>>>
Hi Alice!
Hi Bob!
Age: 32 year, name: Charlie?
6 异常
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => {
println("Missing file exception")}
case ex: IOException => {
println("IO Exception") }
} finally {
println("Exiting finally...")
throw new RuntimeException("n must be even")
}
7 类
7.1 class
7.1.1 定义
- 构造函数
构造函数不是特殊的方法,他们是除了类的方法定义之外的代码。
class MyClass(x: Int, y: Int) { // Defines a new type MyClass with a constructor
require(y > 0, "y must be positive") // precondition, triggering an IllegalArgumentException if not met
def this (x: Int) = { ... } // auxiliary constructor
def nb1 = x // public method computed every time it is called
def nb2 = y
private def test(a: Int): Int = { ... } // private method
val nb3 = x + y // computed only once
override def toString = // overridden method
member1 + ", " + member2
}
new MyClass(1, 2) // creates a new object of type
7.1.2 承继
abstract class TopLevel { // abstract class
def method1(x: Int): Int // abstract method
def method2(x: Int): Int = { ... }
}
class Level1 extends TopLevel {
def method1(x: Int): Int = { ... }
override def method2(x: Int): Int = { ...} // TopLevel's method2 needs to be explicitly overridden
}
object MyObject extends TopLevel { ... } // defines a singleton object. No other instance can be created
7.1.3 Case Classes
Case Class 是一种特殊的class类型,默认的case class 是不可变类型 .可以通过值比较.
基本的定义如下
case class Point(x: Int, y: Int)
可以不通过new 关键字实例化
val point = Point(1, 2)
val anotherPoint = Point(1, 2)
val yetAnotherPoint = Point(2, 2)
比较
if (point == anotherPoint) {
println(point + " and " + anotherPoint + " are the same.")
} else {
println(point + " and " + anotherPoint + " are different.")
}
// Point(1,2) and Point(1,2) are the same.
if (point == yetAnotherPoint) {
println(point + " and " + yetAnotherPoint + " are the same.")
} else {
println(point + " and " + yetAnotherPoint + " are different.")
}
// Point(1,2) and Point(2,2) are different.
7.2 object 单例
作为一个定义的类的单例
object IdFactory {
private var counter = 0
def create(): Int = {
counter += 1
counter
}
}
val newId: Int = IdFactory.create()
println(newId) // 1
7.3 Traits特质
类似于java8的借口
是一些字段和行为的集合,可以扩展或混入(mixin)你的类中。
trait Car {
val brand: String
}
trait Shiny {
val shineRefraction: Int
}
class BMW extends Car {
val brand = "BMW"
}
通过with关键字,一个类可以扩展多个特质:
class BMW extends Car with Shiny {
val brand = "BMW"
val shineRefraction = 12
}
8 collection 内置数据结构
Immutable Collections 不可变对象
- List (linked list, provides fast sequential access)
- Stream (same as List, except that the tail is evaluated only on demand)
- Vector (array-like type, implemented as tree of blocks, provides fast random access)
- Range (ordered sequence of integers with equal spacing)
- String (Java type, implicitly converted to a character sequence, so you can treat every string like a Seq[Char])
- Map (collection that maps keys to values)
- Set (collection without duplicate elements)
Mutable Collections 可变对象
- Array (Scala arrays are native JVM arrays at runtime, therefore they are very performant)
- Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types