Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

string
scala
array
communitycreator

What is the mkString() function of an array in Scala?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 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)

    // print array in normal way
    print(randomNumbers + "\n")   // [I@7e4204e2
    print(fruits + "\n")          // [Ljava.lang.String;@b7c4869
    print(cgpas)                  // [D@740d2e78

    // print with mkString()
    print("\n"+randomNumbers.mkString("-"))  // 34-2-5-70-1
    print("\n"+fruits.mkString(" "))         // Pineapple Banana Orange
    print("\n"+cgpas.mkString(","))          // 3.4,4.5,2.5,0.5
}
Using the mkString() on Arrays in Scala

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.

RELATED TAGS

string
scala
array
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring