Traversable : Copying operations
- Operations: copyToBuffer, copyToArray
- Goals: As their names imply, these copy collection elements to a buffer or array, respectively.
> val l = List(1, 2, 3) l: List[Int] = List(1, 2, 3) > var a = Array[Int]() a: Array[Int] = Array() > l.copyToArray(a) > a res1: Array[Int] = Array() > var a = Array[Int](4, 5, 6) a: Array[Int] = Array(4, 5, 6) > l.copyToArray(a) > a res3: Array[Int] = Array(1, 2, 3)
Exercise: Fix the Bug
There is a problem in this code belllow. When copyToArray is executed an empty array is always returned:
List(1,2,3).copyToArray > Array()
This code should return:
List(1,2,3).copyToArray > Array(1, 2, 3)
You have to fix the code bellow to ensure that this function works correctly.
From the documentation
def copyToArray(xs: Array[A]): Unit
Copies the elements of this list to an array. Fills the given array xs with values of this list. Copying will stop once either the end of the current list is reached, or the end of the target array is reached.
Look at how to allocate an Array in the documentation