简体   繁体   中英

Why is mkString not working in Scala?

I can't get an array to print like a string normally in Scala

  val a = Array("woot","yeah","ok then").sorted

  for (i <- a.length-1 to 0 by -1)
    println(s"$i: ${a(i)}")

  val ab = ArrayBuffer(for (e <- a if e != null) yield e*3)

  println(ab.mkString(" "))

For some reason, this prints:

2: yeah
1: woot
0: ok then
ArrayBuffer([Ljava.lang.String;@5034c75a)

And I was expecting it to print "yeahyeahyeah wootwootwoot ok thenok thenok then" , that is, the items in the array (as strings) separated by a space. Why isn't it working and what am I doing wrong?

EDIT: ok, it was showing that because I was initializing ab to be a one-element ArrayBuffer with that array as the element instead of the elements of that inner array being separate elements of the array buffer.

If you want to print each element of the array, concatenated three times, with spaces between the entries, then it's just:

println((for (e <- a) yield e * 3).mkString(" "))

it gives:

ok thenok thenok then wootwootwoot yeahyeahyeah

(and this is the right order, because you wanted it sorted alphabetically, and o < w < y )

If you want to reverse the array before printing, you can initialize it to

val a = Array("woot","yeah","ok then").sorted.reverse

我想你的意思是

val ab = ArrayBuffer((for (e <- a if e != null) yield e*3): _*)

Some shorter answer using more functional approach:

val a = Array("woot","yeah","ok then").sorted.reverse
a.map(_ * 3).map(elem => print(elem + " ")

Edit: If you want to have a result in some new variable you can do that:

val string = a.map(_ * 3).mkString(" ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM