list - 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)
}
解决方案
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.
因此,这取决于您需要执行的操作的大小和类型,这在性能方面更可取。
推荐阅读
- javascript - 为什么我不能使用这个特定的方法返回这个函数?
- laravel - 在 Codeigniter 项目中集成 Laravel 库
- gitlab - 当我们在前一阶段失败时如何停止 gitlab-ci.yml 中的工作
- c# - 列出 OrderBy 值 < 值
- dart - 在 BlocBuilder 中将类初始化为模型并出现错误
- javascript - 如何从打字稿中的对象键字符串中提取确切的联合类型?
- excel - 如何使用if语句匹配多个条件并删除表中的选定行
- scala - 在databricks上使用df.bulkCopyToSqlDB时,sql批量插入永远不会完成1000万条记录
- c# - 为什么 .Net Framework 的加密如此复杂?
- javascript - Javascript:如何显示默认选项卡内容但隐藏其他选项卡内容