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

Idiomatically:

fun main(args: Array<String>) {
  val someList = arrayOf("United", "Chelsea", "Liverpool")
  println(someList.joinToString(" "))
}

This makes use of type inference, an immutable value, and well-defined methods for doing well-defined tasks.

The joinToString() method also allows prefix and suffix to be included, a limit, and truncation indicator.


Array has a forEach method as well which can take a lambda:

var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach { System.out.print(it) }

or a method reference:

var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach(System.out::print)

I know three ways to do this:

(0 until someList.size).forEach { print(someList[it]) }
someList.forEach { print(it) }
someList.forEach(::print)

Hope you enjoyed it :)


You can achieve this using "contentToString" method:

var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
  println(someList.contentToString())

O/p:
[United, Chelsea, Liverpool]e

Tags:

Java

Kotlin