Seq [Int]和List [Int]之间的区别和转换 [英] The difference and conversion between Seq[Int] and List[Int]

查看:311
本文介绍了Seq [Int]和List [Int]之间的区别和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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)

是否有人对 Seq [Int] = List(1、2、3)是什么意思?这不是说 Seq(1,2,3)返回一个列表吗? Seq [Int] List [Int] 有什么区别?
以及如何在 Seq List 之间进行转换?

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?

推荐答案

Seq 是序列和 列表 是该接口的具体实现。

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

每个列表的实例已经是一个 Seq ,因此无需进行任何转换。您可以使用 toSeq 方法,但我认为没有任何理由这样做。
要将 Seq 转换为 List ,请使用 toList 方法。

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.

这篇关于Seq [Int]和List [Int]之间的区别和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆