首页 > 解决方案 > scala - 无法解析符号::

问题描述

我是 Scala 的新手,并且有一些关于为什么string::List()工作List()::s不工作的问题?我也想知道 ListBuffer 是否工作得更好 ::

val columnNames :List[String] = ['foo','bar']
val work :List[String] = List()
for (s <- columnNames) {
  s match {
     //this doesn't compile
     //case workPattern => work :: s
     //this works        
     case workPattern => s :: work
     // this also works
     case workPattern => work :: List(s)
}

标签: listscala

解决方案


a :: b字面意思是“a在列表的开头添加一个元素b”。a它以头部和b尾部创建新列表。

要将元素附加到列表中,您可以使用++ 或类似的东西 work ::: "foo" :: Nil,当然,后者效率不高。

对于问题的第二部分,如文档中所述:

Time: List has O(1) prepend and head/tail access. 
Most other operations are O(n) on the number of elements in the list. 
This includes the index-based lookup of elements, length, append and reverse.
Space: List implements structural sharing of the tail list. 
This means that many operations are either zero- or constant-memory cost.

因此,这取决于您需要执行的操作的大小和类型,这在性能方面更可取。


推荐阅读