The mkString()
function of an array is used to display all elements of an array as a string using a separator string. This method is very useful because, ordinarily, the elements will not be displayed when printing an array.
array.mkString(separator)
separator
: This is the string we want to use and separate each of the element of our array.
The value returned is a string representation of elements present in an 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)// print array in normal wayprint(randomNumbers + "\n") // [I@7e4204e2print(fruits + "\n") // [Ljava.lang.String;@b7c4869print(cgpas) // [D@740d2e78// print with mkString()print("\n"+randomNumbers.mkString("-")) // 34-2-5-70-1print("\n"+fruits.mkString(" ")) // Pineapple Banana Orangeprint("\n"+cgpas.mkString(",")) // 3.4,4.5,2.5,0.5}
mkString()
function to print the arrays using different separators.