【问题标题】:List of lists as Map value does not compile作为 Map 值的列表列表无法编译
【发布时间】:2016-12-29 16:40:40
【问题描述】:

我在 Scala 中有一个 Map,其中的值是列表列表。我尝试使用以下代码添加一个值:

var map = Map[String,List[List[String]]]()
val list1 = List ("A111", "B111")
var listInMap = map.getOrElse("abc", List[List[String]]())
listInMap += list1   // this line does not compile
map += ("abc" -> listInMap)

问题是在listInMap += list1 行中它抛出type mismatch; found : List[String] required: String。如果我需要向列表中添加列表,为什么需要 String?我需要将list1 添加到listInMap

【问题讨论】:

    标签: scala


    【解决方案1】:

    listInMap += list1 等价于listInMap = listInMap + list1+ 运算符未在 List 中为最新的 scala 库 (2.11.8) 定义(在 2.7 中标记为已弃用)。因此,+ 运算符只需将listInMaplist1 的字符串值与最新的scala 库连接起来。

    对于最新的 scala,您可以使用 listInMap = listInMap :+ list1

    另外,请检查:https://stackoverflow.com/a/7794297/1433665,因为在 scala 中附加到列表的复杂度为 O(n)

    【讨论】:

    • listInMap += list1list1 添加到listInMap,反之亦然?我需要将list1 添加到listInMap
    • 嘿@ps0604,是的,你是对的。检查我更新的答案。希望对您有所帮助。
    • 现在我收到此错误:type mismatch; found : List[java.io.Serializable] required: List[List[String]]
    【解决方案2】:

    您的问题是 list1 没有插入到正确的深度/级别。

    这将编译。

    . . .
    map += ("abc" -> (listInMap ++ List(list1)))
    map("abc")  // result: List[List[String]] = List(List(A111, B111))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 2021-11-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多