Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Arrays in Scala

Tags:

If I have DerivedType1:BaseType and DerivedType2:BaseType and Array[DerivedType1] and Array[DerivedType2], what's the most succinct way of combining them into Array[BaseType]?

like image 916
pondermatic Avatar asked Oct 23 '11 06:10

pondermatic


People also ask

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do I append an array in Scala?

Use the :+ Method to Append Elements to an Array in Scala Using :+ , we can append the elements to the existing array without using an auxiliary array. Instead of :+ , we can also use +: to prepend , which means adding elements at the beginning of an array.

How do I combine sets in Scala?

Use the ++= method to merge a sequence into a mutable sequence. Use the ++ method to merge two mutable or immutable sequences. Use collection methods like union , diff , and intersect.


1 Answers

Use the ++ method on Array.

scala> class A; class B extends A; class C extends A
defined class A
defined class B
defined class C

scala> Array(new B, new B) ++ Array(new C, new C)
res33: Array[A] = Array(B@b7501b, B@ec5359, C@1540d0c, C@124a927)
like image 164
missingfaktor Avatar answered Sep 21 '22 12:09

missingfaktor