Better one liner to generate n spaces
Yes, this is a funny question, but I want to learn how to use collection operations such as map, shrink and collapse correctly.
I did this:
scala> Range(0,3) map(_=>" ") reduceLeft(_+_)
res15: java.lang.String = " "
What's the best idiomatic way to generate n spaces with a collection operation?
source to share
Technically the next "collection operation" I think is because it StringOps
is in the package scala.collection.immutable
:
scala> " " * 3
res1: String = " "
What's going on here is what is " "
implicitly converted to an instance StringOps
using scala.Predef.augmentString
and then *
to StringOps
.
Update: I meant this kind of as a joke of sorts, since this is clearly not what you mean by "collect operation" - it is not a higher order function like map
or reduce
. I would definitely use my version (version StringOps
) in real code, but if you want to use higher order functions (for educational reasons, for a similar problem, etc.), I think your version is pretty close to idiomatic. I personally used until
to plot a range and reduce
instead of reduceLeft
(since concatenation is associative) -ie, pretty much what virtualeyes wrote in his or her answer.
source to share