What is the mkString() function of an array in Scala?
Overview
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.
Syntax
array.mkString(separator)
Syntax for the mkString() method
Parameters
separator: This is the string we want to use and separate each of the element of our array.
Return value
The value returned is a string representation of elements present in an array.
Example
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}
Explanation
- Lines 3–5: We create some arrays.
- Lines 8–10: We print the arrays to the console normally. However, they are printed in a way that is not understandable.
- Lines 13–15: We use the
mkString()function to print the arrays using different separators.