构建 LinearSeq

Construct LinearSeq

在 Scala 中,LinearSeq 和 IndexedSeq 是 Seq 的子特征。 如果我构建一个 IndexedSeq,比如

IndexedSeq(1)

我得到了默认实现,即 Vector

IndexedSeq[Int] = Vector(1)

但是如果我尝试构造一个 LinearSeq,如

LinearSeq(1)

我得到一个错误而不是默认实现列表

<console>:8: error: not found: value LinearSeq
          LinearSeq(1)
          ^

请解释此行为。

您需要先导入它...

import scala.collection.immutable.LinearSeq

import scala.collection.LinearSeq

回复:

@ import scala.collection.immutable.LinearSeq 
import scala.collection.immutable.LinearSeq
@ LinearSeq(1) 
res3: LinearSeq[Int] = List(1)

要回答为什么需要导入这个但 IndexedSeq 有效,请参阅默认导入的 scala 包对象的来源:

type IndexedSeq[+A] = scala.collection.IndexedSeq[A]
val IndexedSeq = scala.collection.IndexedSeq

所以语言的设计者将 IndexedSeq 引入了默认范围,他们对 TraversableIterableSeqList 和其他几个也做了同样的事情为了方便起见,但他们没有为 LinearSeq 这样做,这可能是合理的,因为我从未在我的代码中明确使用过它,而我使用了那里的大多数其他东西。