scala学习笔记-容器

可变和不可变(Scala默认不可变集合类)
  1. val和var
  2. mutable和immutable
  3. 补充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

  1. 唯一的抽象操作是foreach,需要实现Traversable的容器(collection)类仅仅需要定义与之相关的方法,其他所有方法可都可以从Traversable中继承。
  2. Traversable同时定义的很多具体方法,如下表所示。这些方法可以划分为以下类别(相加操作,map操作,转换器、拆分、拷贝、元素检索等等) 容器的上层trait:Iterable
  3. 这个trait内所有的方法都基于一个抽象方法iterator
//eg:Traversable trait里继承来的foreach方法在这里也是利用iterator实现
def foreach[U](f: Elem => U): Unit = {
  val it = iterator
  while (it.hasNext) f(it.next())
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,959评论 0 23
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,921评论 0 38
  • 王者荣耀是一个年轻人都知道的游戏,甚至老年人中很多人都玩,我是从2017年开始玩到现在,中间经历过三次卸载,四次下...
    给生活吐口水阅读 338评论 0 1
  • 岁月匆匆,时光荏苒,村头,路口,曾经那弱不经风的小树苗,已成大树,伫立在村口,迎着风,望着日,喝着露水。 看,它那...
    牧野俊风阅读 327评论 0 3