I am currently trying out things in Scala, trying to get accustomed to functional programming as well as leaning a new language again (it's been a while since last time).
Now given a list of strings if I want to merge them into one long string (e.g. "scala", "is", "fun" => "scalaisfun"
) I figured one way to do it would be to do a foldRight
and apply concatenation on the respective elements. Another way, admittedly much simpler, is to call mkString
.
I checked on github but couldn't really find the source code for the respective functions (any help on that would be appreciated), so I am not sure how the functions are implemented. From the top of my head, I think the mkString
is more flexible but it feels that there might be a foldRight
in the implementation somewhere. Is there any truth to it?
Otherwise the scaladocs mention that mkString
calls on toString
for each respective element. Seeing that they are already strings to start with, that could be one negative point for mkString
in this particular case. Any comments on the pros and cons of both methods, with respect to performance, simplicity/elegance etc?
Simple answer: use
mkString
.someString.toString
returns the same object.mkString
is implemented with a singleStringBuilder
and it creates only 1 new string. WithfoldLeft
you'll createN-1
new strings.You could use
StringBuilder
infoldLeft
, it will be as fast asmkString
, butmkString
is shorter:Im memory serves,
mkString
uses a StringBuilder to build the String which is efficient. You could accomplish the same thing using a ScalaStringBuilder
as the accumulator tofoldRight
, but why bother ifmkString
can already do all that good stuff for you. PlusmkString
gives you the added benefit of also including an optional delimiter. You could do that infoldRight
but it's already done for you withmkString
Don't use
foldRight
unless you really need it, as it will overflow your stack for large collections (for some types of collections).foldLeft
orfold
will work (does not store intermediate data on the stack), but will be slower and more awkward thanmkString
. If the list is nonempty,reduce
andreduceLeft
will also work.