How to convert an integer array to a string array in Scala

1 Answer

0 votes
object ArrayConversionExample {

  /**
   * Converts an Array[Int] to an Array[String] idiomatically.
   *
   * @param intArray The input array of integers.
   * @return A new Array[String] containing the string representation of each integer.
   */
  def convertIntArrayToStringArray(intArray: Array[Int]): Array[String] = {
    // .map transforms each element in the array. 
    // _.toString is a concise shorthand lambda for (x => x.toString).
    intArray.map(_.toString)
  }

  def main(args: Array[String]): Unit = {
    val numbers: Array[Int] = Array(1, 2, 3, 4, 5)
    
    // Call the conversion function
    val strings: Array[String] = convertIntArrayToStringArray(numbers)
    
    // Print the resulting array elements and their types
    strings.foreach(println) 
  }
}


/*
run:

1
2
3
4
5

*/

 



answered 14 hours ago by avibootz
...