Scala变量声明
• var x : Int = 7
• val x = 7 //自动类型推导
• val y = “hi” //只读,相当于Java里的final
Scala函数
Scala泛型
var arr = new Array[Int](8)
var lst = List(1,2,3) //1st的类型是List[Int]
//索引访问
arr(5) = 7
println(lst(1))
def square(x : Int) : Int = x * x // 函数名(参数)返回类型 = 函数体
def square(x : Int) : Int = {x*x} //在{}block中的最后一个值将被自动返回return
def announce(text : String) {println(text)} //没有返回值
Scala—FP的方式处理集合
val list = List(1,2,3)
list.foreach(x=>println(x)) //打印出1,2,3
list.foreach(println) //省略了,效果同上list.map(x => x + 2) //List(3,4,5)
list.map(_+2) //_代表list中每个元素
list.filter(x => x % 2 == 1) //List(1,3)
list.filter(_ % 2 == 1) //同上 list.reduce((x,y) => x + y) //任意两个参数相加,最后结果:6
list.reduce(_+_) //同上