Dishonered
Dishonered

Reputation: 8841

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

This is my code

    fun main(args : Array<String>){
     var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")

      //How do i print the elements using the print method in a single line?
    }

In java i would do something like this

someList.forEach(java.lang.System.out::print);

Upvotes: 52

Views: 81186

Answers (8)

Sohaib Ahmed
Sohaib Ahmed

Reputation: 3062

Simply do this, no need to use loop and iterate by yourself. Reference

println(someList.joinToString(","))

Upvotes: 4

PKDev
PKDev

Reputation: 21

If it is solely for printing purpose then a good one liner is

 var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
 println(java.util.Arrays.toString(someList))

Upvotes: 0

delitescere
delitescere

Reputation: 816

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.

Upvotes: 54

WitWicky
WitWicky

Reputation: 291

You can achieve this using "contentToString" method:

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

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

Upvotes: 25

JPO
JPO

Reputation: 91

You could

fun main(args : Array<String>){
  var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")

  val sb = StringBuilder()
  for (element in someList) {
      sb.append(element).append(", ")
  }
  val c = sb.toString().substring(0, sb.length-2)
  println(c)
}

gives

United, Chelsea, Liverpool

alternatively you can use

print(element)

in the for loop, or even easier use:

var d = someList.joinToString()
println(d)

Upvotes: 4

twupack
twupack

Reputation: 196

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

Upvotes: 11

Michael
Michael

Reputation: 44110

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)

Upvotes: 44

statut
statut

Reputation: 909

You can do the same:

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

Upvotes: 4

Related Questions