Why no immutable arrays in scala standard library?

前端 未结 7 1551
死守一世寂寞
死守一世寂寞 2020-12-23 21:27

Scala has all sorts sorts of immutable sequences like List, Vector,etc. I have been surprised to find no implementation of immutable indexed sequence backed by a simple arra

7条回答
  •  一向
    一向 (楼主)
    2020-12-23 22:09

    The point of the scala Array class is to provide a mechanism to access the abilities of Java arrays (but without Java's awful design decision of allowing arrays to be covariant within its type system). Java arrays are mutable, hence so are those in the scala standard library.

    Suppose there were also another class immutable.Array in the library but that the compiler were also to use a Java array as the underlying structure (for efficiency/speed). The following code would then compile and run:

    val i = immutable.Array("Hello")
    i.asInstanceOf[Array[String]](0) = "Goodbye"
    println( i(0) ) //I thought i was immutable :-(
    

    That is, the array would really be mutable.

提交回复
热议问题