Zotov Zotov - 27 days ago 9
Scala Question

Trying to append to Iterable[String]

I'm trying to add another string to Iterable[String] for easy concatenation, but the result is not what I expect.

scala> val s: Iterable[String] = "one string" :: "two string" :: Nil
s: Iterable[String] = List(one string, two string)

scala> s.mkString(";\n")
res3: String =
one string;
two string

scala> (s ++ "three").mkString(";\n")
res5: String =
one string;
two string;
t;
h;
r;
e;
e


How should I should I rewrite this snippet to have 3 string in my iterable?

Edit: I should add, that order of items should be preserved

Answer

++ is for collection aggregation. There is no method +, :+ or add in Iterable, but you can use method ++ like this:

scala> (s ++ Seq("three")).mkString(";\n")
res3: String =
one string;
two string;
three