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
++ 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
The ++ function is waiting for a Traversable argument. If you use just "three", it will convert the String "three" to a list of characters and append every character to s. That's why you get this result.
Instead, you can wrap "three" in an Iterable and the concatenation should work correctly :
scala> (s ++ Iterable[String]("three")).mkString(";\n")
res6: String =
one string;
two string;
three
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With