Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to append to Iterable[String]

Tags:

iterable

scala

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

like image 407
zbstof Avatar asked Dec 12 '22 14:12

zbstof


2 Answers

++ 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
like image 95
senia Avatar answered Jan 03 '23 03:01

senia


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
like image 27
mguillermin Avatar answered Jan 03 '23 01:01

mguillermin