scala中Seq [Int]和List [Int]之间的差异和转换?

Han*_*Sun 5 containers functional-programming scala type-conversion

当我Seq(1,2,3)在REPL中输入时,它返回给我List(1,2,3)

scala> Seq(1,2,3)
res8: Seq[Int] = List(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

因此,我认为List(1,2,3)可能是类型List[Int].我试图指定分配给变量的类型Seq(1,2,3),但出乎意料的是,REPL抱怨如下:

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)
Run Code Online (Sandbox Code Playgroud)

有没有人有什么Seq[Int] = List(1, 2, 3)意思?它不应该意味着Seq(1,2,3)返回一个列表吗?Seq[Int]和之间有什么区别List[Int]?以及如何转换 SeqList

Rad*_*sky 8

Seq是序列的基本特征(接口),List是该接口的具体实现.

每个实例List都是Seq如此,所以不需要转换任何东西.您可以使用toSeq方法,但我认为没有任何理由这样做.转换SeqList使用toList方法.

  • 要求“Seq”与要求“汽车”具有相同的含义。任何车。工厂为您提供了一辆不错的 Toyota - 在我们的例子中是“List”的实例。您的请求是通用的,而响应是具体的。如果您希望 Toyota 直接要求它 - 明确设置一个 `List`。 (3认同)