Zotov Zotov - 1 year ago 122
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;

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 Source

++ 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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download