Scala列表到Seq

时间:2018-07-12 09:58:08

标签: scala scala-collections

我有一个这样的scala代码

val tokens = List("the", "program", "halted")
val test = for (c <- tokens) yield Seq(c) 

此处测试返回的是List(Seq(String)),但我期望仅使用Seq(String)。也许对于一个有经验的人来说这很简单,但是我尝试了所有我在基本水平上都知道但没有外观的方法。如果有人觉得很简单,请帮助我。

3 个答案:

答案 0 :(得分:2)

tokens.toSeq可以,但是如果您在命令行中键入此命令,您将看到Seq只会在幕后创建一个List

scala> val tokens = List("the", "program", "halted")
tokens: List[String] = List(the, program, halted)

scala> tokens.toSeq
res0: scala.collection.immutable.Seq[String] = List(the, program, halted)

Seq很有趣。如果您的数据更适合存储在List中,则会将其转换为列表。否则,它将变成Vector(向量本身就很有趣...)-因为SeqListVector的超类型。如果有的话,除非您有特定的用例,否则您应该默认使用Vector而不是其他集合类型,但这是另一个问题的答案。

其他选择当然是:

scala> val test: Seq[String] = tokens
test: Seq[String] = List(the, program, halted)

scala> val test2: Seq[String] = for (token <- tokens) yield token
test2: Seq[String] = List(the, program, halted)

scala> val test3 = (tokens: Seq[String])
test3: Seq[String] = List(the, program, halted)

scala> val test4: Seq[String] = tokens.mkString(" ").split(" ").toSeq
test4: Seq[String] = WrappedArray(the, program, halted)

(开个玩笑而已)

可是,您可以仅将变量类型指定为Seq[String],Scala将根据其处理SeqListVector的方式将其视为此类等等。

答案 1 :(得分:1)

ListSeq的子类型。您根本不需要任何理解,只需将类型归因于

val test: Seq[String] = tokens

或:

val test = (tokens: Seq[String])

答案 2 :(得分:0)

首先List扩展Seq在幕后,因此您实际上有一个Seq。您可以在定义级别下转换。

val tokens: Seq[String] = List("the", "program", "halted")

现在要回答您的问题,在Scala集合中,转换通常可以通过toXXX方法来实现。

val tokens: Seq[String] = List("the", "program", "halted").toSeq

在更高级的阅读中,请查看CanBuildFrom,这是幕后的魔法。

相关问题