How to print all the elements of a String array in Kotlin in a single line?


In this article, we will take an example and show how to print all the elements of a String array in a single line using a Kotlin library class. In order to do that, we will use a String function called joinToString(), provided by the Kotlin library.

As per the Kotlin documentation, the function definition looks like this −

fun <T> Array<out T>.joinToString(
   // the String will be separated by this
   separator: CharSequence = ", ",

   // This will be added as prefix to the String
   prefix: CharSequence = "",

   // This will be added as postfix to the String
   postfix: CharSequence = "",

   // This number of element will be printed,
   // the remaining elements will be denoted but truncated sequence
   limit: Int = -1,
   truncated: CharSequence = "...",

   //any transformation required over the String
   transform: ((T) -> CharSequence)? = null
): String

This function takes several attributes in order to convert an arrayList into a String.

Example - Printing all elements of a String array in a single line

fun main(args: Array<String>) {

   val mylist = listOf("Jam", "bread", "apple", "mango")

   println(
      mylist.joinToString(
         prefix = "[",
         separator = "-",
         postfix = "]",
         truncated = "...",
      )
   )
}

Output

On execution, it will produce the following output −

[Jam-bread-apple-mango]

Updated on: 01-Mar-2022

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements