【问题标题】:scala - cannot resolve symbol ::scala - 无法解析符号::
【发布时间】:2021-03-28 19:57:34
【问题描述】:

我是 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)
}

【问题讨论】:

    标签: list scala


    【解决方案1】:

    a :: b 字面意思是“在列表b 的开头添加一个元素a”。 它以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.
    

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

    【讨论】:

      【解决方案2】:

      您在s :: work 调用的函数是List.::。 Scala String 只是 Java 字符串的别名,因此不会暴露诸如 :: 之类的运算符。 s :: work 等价于work.::(s)

      有关更多信息,您可以参考伟大的 Alvin Alexander 的 How to add elements to a List in Scala (List, ListBuffer)Scala List class examples: range, fill, tabulate, appending, foreach, more ...

      【讨论】:

        猜你喜欢
        • 2017-03-29
        • 1970-01-01
        • 2021-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-20
        • 1970-01-01
        • 2023-02-26
        相关资源
        最近更新 更多