We use the clone()
method to clone an array in Scala. An array clone is another array that is equal to the original array it cloned.
array.clone()
array
: This is the array to be cloned.
It returns an array with elements of the array
array.
object Main extends App {// Create some arraysval randomNumbers = Array(34, 2, 5, 70, 1)val fruits = Array("Pineapple", "Banana", "Orange")val cgpas : Array[Double] = Array(3.4, 4.5, 2.5, 0.5)val names = new Array[String](3)names(0) = "Amara"names(1) = "Funke"names(2) = "Ade"// Create clonesval randomNumbersClone = randomNumbers.clone()val fruitsClone = fruits.clone()val cgpasClone = cgpas.clone()val namesClone = names.clone()// Print the array clones as stringsprint(randomNumbersClone.mkString(" "))print("\n"+ fruitsClone.mkString(" "))print("\n"+ cgpasClone.mkString(" "))print("\n"+ namesClone.mkString(" "))}
clone()
function.mkString()
method to get the string representation of the cloned arrays' elements. Then, we print the clones to the console.