Prasanna Sundar
Prasanna Sundar

Reputation: 1660

unexpected behaviour of "grouped" in scala

I am learning scala right now. When I wrote a statement as below,

"abcdpqrs".split("").grouped(2).map(_.mkString("")).mkString("|")

i expected it to print,

ab|cd|pq|rs

but instead it is printing,

a|bc|dp|qr|s

I find this behaviour erratic. Am I missing something or is there anything else which can partition the list as I expected?

Upvotes: 0

Views: 166

Answers (1)

Hamish
Hamish

Reputation: 1015

You're getting a|bc|dp|qr|s as a result because of split("")

scala> "abcdpqrs".split("")
res0: Array[String] = Array("", a, b, c, d, p, q, r, s)

If you do this without split("") you get

scala> "abcdpqrs".grouped(2).map(_.mkString("")).mkString("|")
res4: String = ab|cd|pq|rs

which I think is what you want

EDIT

For the record @marstran has helpfully pointed out that this only happens in java 7 - the behaviour of split was changed with java 8 and instead split("") will give

scala> "abcdpqrs".split("")
res0: Array[String] = Array(a, b, c, d, p, q, r, s)

Upvotes: 3

Related Questions