可变和不可变(Scala默认不可变集合类)
- val和var
- mutable和immutable
- 补充string是容器类中的一个immutable实现,所以字符串是不可变的集合
val a =new testimmu(1,1)
val b =new testimmu(2,2)
val c =new testimmu(3,3)
var map1 = immutable.Map("a"->"first","b"->"second")
map1+=("c"->"thrid")
val map3 = immutable.Map("a"->"first","b"->"second")
val map5 = immutable.Map("a"->a,"b"->b,"c"->c)
// map3+=("c"->"thrid")
//immutable不可变,1虽模拟了map的扩展,但本质是返回一个新的集合。所以map3会出错
var map2 = mutable.Map("a"->"first","b"->"second")
map2+=("c"->"thrid")
val map4 = mutable.Map("a"->"first","b"->"second")
map4+=("c"->"thrid")
val map6 = mutable.Map("a"->a,"b"->b,"c"->c)
a.setParam1(111111)
println(map5)//集合不可变,但是若集合对象是可变对象,则集合终归还是可变的(容器内的对象状态发生变化)
println(map6)
val numberArray=new Array[Int](10)
strArray(0)="First Element"//数组长度不可变,数组内容可变
yield
先看下在Programming scala里yield的定义: For each iteration of your for loop, yield generates a value which will be remembered. It's like the for loop has a buffer you can't see, and for each iteration of your for loop, another item is added to that buffer. When your for loop finishes running, it will return this collection of all the yielded values. The type of the collection that is returned is the same type that you were iterating over, so a Map yields a Map, a List yields a List, and so on. Also, note that the initial collection is not changed; the for/yield construct creates a new collection according to the algorithm you specify.
大致意思是,每次for循环,yield都会生成一个会被记住的值。就像在循环的时候有一个无形的Buffer,每次迭代,另一个元素就会放入到Buffer里。当你的循环结束,将会返回被yield的值的一个集合。集合的类型和被迭代的集合类型一样,如果迭代的是list,返回list,如果是map就返回map
容器
容器的顶级trait:Traversable
- 唯一的抽象操作是foreach,需要实现Traversable的容器(collection)类仅仅需要定义与之相关的方法,其他所有方法可都可以从Traversable中继承。
- Traversable同时定义的很多具体方法,如下表所示。这些方法可以划分为以下类别(相加操作,map操作,转换器、拆分、拷贝、元素检索等等) 容器的上层trait:Iterable
- 这个trait内所有的方法都基于一个抽象方法iterator
//eg:Traversable trait里继承来的foreach方法在这里也是利用iterator实现
def foreach[U](f: Elem => U): Unit = {
val it = iterator
while (it.hasNext) f(it.next())
}