scala 试图附加到 Iterable[String]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16773535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:20:08  来源:igfitidea点击:

Trying to append to Iterable[String]

scalaiterable

提问by zbstof

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

我正在尝试将另一个字符串添加到 Iterable[String] 以便于连接,但结果不是我所期望的。

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?

我应该如何重写此代码段以在可迭代对象中包含 3 个字符串?

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

编辑:我应该补充一点,应该保留项目的顺序

回答by senia

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

++用于集合聚合。有没有一种方法+:+或者addIterable,但是你可以使用的方法++是这样的:

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

回答by mguillermin

The ++function is waiting for a Traversableargument. 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.

++函数正在等待一个Traversable参数。如果您只使用"three",它会将字符串转换"three"为字符列表并将每个字符附加到s. 这就是为什么你会得到这个结果。

Instead, you can wrap "three" in an Iterableand the concatenation should work correctly :

相反,您可以将“三个”包裹在一个中Iterable,并且串联应该可以正常工作:

scala> (s ++ Iterable[String]("three")).mkString(";\n")
res6: String =
one string;
two string;
three

回答by Joerg Schmuecker

I like to use toBuffer and then +=

我喜欢使用 toBuffer 然后 +=

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.

我不知道为什么标准库不支持这个操作。您也可以使用 toArray 但如果添加多个元素,这将降低性能 - 我会假设 - 因为如果添加另一个元素,缓冲区应该返回自身。