Introduction to Scala Part2 : Collections
Bubu
6,466 views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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.
Hints
Hint #1
From the documentation
def copyToArray(xs: Array[A]): Unit
[use case]
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.
Hint #2
Look at how to allocate an Array in the documentation
should copy list to array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package fp101.tp02.collections
object ExerciceCopying {
/**
* Fix the code below.
*/
def copyToArray: Array[Int] = {
val l = List(1, 2, 3)
val a = Array[Int]()
l.copyToArray(a)
a
}
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content