第一天:scala总结
函数
scala> def f1(a1: String, a2: Int = 10) = a1+a2
f1: (a1: String, a2: Int)String
scala> f1("he")
res1: String = he10
a2 是默认并且初始化的参数
def sum(a: Int*): Int = {
var result = 0
for (el <- a)
result += el
result
}
数组:
scala> val buf = ArrayBuffer(10)
buf: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10)
scala> buf += 10
res6: buf.type = ArrayBuffer(10, 10)
scala> buf += (1,2,3,4)
res8: buf.type = ArrayBuffer(10, 10, 1, 2, 3, 4)
scala> buf ++= Array(1,20,30,4)
res9: buf.type = ArrayBuffer(10, 10, 1, 2, 3, 4, 1, 20, 30, 4)
println(
sum(
1 to
20: _*)) 输出结果:210 其中_* 的作用提取 前面集合里的每一个元素
数组可以可以实现删除指定的元素
buf.trimStart(1) 删除数据以1开始的元素数据
buf.trimEnd(4) 删除数据以4结尾的元素数据
lazy:打开第一次的时候使用,比较耗时
移除数组中第一个是负数后的所有元素
val a = Range(-4, 4)
var firstPre = false
a.filter {
case x if x < 0 && !firstPre => firstPre = !firstPre ; true
case x if x < 0 && firstPre => false
case _ => true
}.foreach(println)