Introduction to Scala Part2 : Collections


Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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:

> Array()

This code should return:

> Array(1, 2, 3)

You have to fix the code bellow to ensure that this function works correctly.


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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content