How to efficient copy an Array to another in Scala?

前端 未结 4 1501
轻奢々
轻奢々 2021-01-12 03:28

How I can use another way to copy a Array to another Array?

My thought is to use the = operator. For example:

         


        
4条回答
  •  [愿得一人]
    2021-01-12 03:44

    The shortest and an idiomatic way would be to use map with identity like this:

    scala> val a = Array(1,2,3,4,5)
    a: Array[Int] = Array(1, 2, 3, 4, 5)
    

    Make a copy

    scala> val b = a map(identity)
    b: Array[Int] = Array(1, 2, 3, 4, 5)
    

    Modify copy

    scala> b(0) = 6
    

    They seem different

    scala> a == b
    res8: Boolean = false
    

    And they are different

    scala> a
    res9: Array[Int] = Array(1, 2, 3, 4, 5)
    
    scala> b
    res10: Array[Int] = Array(6, 2, 3, 4, 5)
    

    This copy would work with all collection types, not just Array.

提交回复
热议问题