Reputation: 1072
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
Upvotes: 4
Views: 15367
Reputation: 111
I like to use toBuffer and then +=
scala> val l : Iterable[Int] = List(1,2,3)
l: Iterable[Int] = List(1, 2, 3)
scala> val e : Iterable[Int] = l.toBuffer += 4
e: Iterable[Int] = ArrayBuffer(1, 2, 3, 4)
or in your example:
scala> (s.toBuffer += "three").mkString("\n")
I have no idea why this operation isn't supported in the standard library. You can also use toArray but if you add more than one element this will be less performant - I would assume - as the buffer should return itself if it another element is added.
Upvotes: 0
Reputation: 38045
++
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
Upvotes: 8
Reputation: 4181
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
Upvotes: 5