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]
?
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With