The difference and conversion between Seq[Int] and List[Int]

妖精的绣舞 提交于 2020-08-19 11:54:51

问题


When I input Seq(1,2,3) in REPL, it returns me List(1,2,3)

scala> Seq(1,2,3)
res8: Seq[Int] = List(1, 2, 3)

Therefore, I thought the List(1,2,3) may be of type List[Int]. And I tried to specify the type for the variable who are assigned to Seq(1,2,3), but unexpectedly, the REPL complains like this:

scala> val a:List[Int]=Seq(1,2,3)
<console>:20: error: type mismatch;
 found   : Seq[Int]
 required: List[Int]
       val a:List[Int]=Seq(1,2,3)

Does anyone have ideas about what Seq[Int] = List(1, 2, 3) mean? Shouldn't it mean Seq(1,2,3) returns a list? What is the difference between Seq[Int] and List[Int]? And how to convert between Seq and List?


回答1:


Seq is a base trait (interface) for sequences and List is a concrete implementation of that interface.

Every instance of List is already a Seq so there's no need to convert anything. You can use toSeq method, but I don't see any reason to do so. To convert Seq to a List use toList method.



来源:https://stackoverflow.com/questions/27478889/the-difference-and-conversion-between-seqint-and-listint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!