I have a scala code like this
val tokens = List("the", "program", "halted")
val test = for (c <- tokens) yield Seq(c)
Here test is returning List(Seq(String)) but I'm expecting Seq(String) only. Maybe it's very simple for an experienced person but I tried all the way which I know in the basic level but no look. Please help me if anyone feels its very easy.
tokens.toSeq
will do, but if you type this into the command line you will see that Seq
will just create a List
under the hood anyway:
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
is interesting. If your data will be better suited to being stored in a List
it will turn it into a list; otherwise, it will turn it into a Vector
(and Vectors are interesting in their own right...) - as Seq
is a supertype of both List
and Vector
. If anything, you should really default to using Vector
over other collection types unless you have a specific use case, but that's an answer to another question.
Other alternatives are of course:
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)
(Just joking about that last one)
The takeaway though is that you can just specify the variable type as Seq[String]
and Scala will treat it as such due to how it handles Seq
, List
, Vector
etc under the hood.
List
is a subtype of Seq
. You don't need any for-comprehensions at all, you only have to ascribe the type:
val test: Seq[String] = tokens
or:
val test = (tokens: Seq[String])
First of all List
extends Seq
behind the scenes, so you do actually have a Seq
. You can downcast at definition level.
val tokens: Seq[String] = List("the", "program", "halted")
Now to answer your question, in Scala collection conversions are often facilitated by toXXX
methods.
val tokens: Seq[String] = List("the", "program", "halted").toSeq
In more advanced reading, look at CanBuildFrom
, which is the magic behind the scenes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.