Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala
communitycreator

How to clone an array in Scala

Theodore Kelechukwu Onyejiaku

Overview

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.

Syntax

array.clone()
Syntax for cloning an array in Scala

Parameters

array: This is the array to be cloned.

Return value

It returns an array with elements of the array array.

Code example

object Main extends App {
// Create some arrays
    val 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 clones 
    val randomNumbersClone = randomNumbers.clone()
    val fruitsClone = fruits.clone()
    val cgpasClone = cgpas.clone()
    val namesClone = names.clone()

    // Print the array clones as strings
    print(randomNumbersClone.mkString(" "))
    print("\n"+ fruitsClone.mkString(" "))
    print("\n"+ cgpasClone.mkString(" "))
    print("\n"+ namesClone.mkString(" "))
}
Cloning an array in Scala

Explanation

  • Lines 3–10: We instantiate and initialize the arrays with some values.
  • Lines 13–16: We get the clones of the arrays we created using the clone() function.
  • Lines 19–22: We use the mkString() method to get the string representation of the cloned arrays' elements. Then, we print the clones to the console.

RELATED TAGS

scala
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring