代码之家  ›  专栏  ›  技术社区  ›  User12547645

如何将集合添加到scala中的集合列表中

  •  0
  • User12547645  · 技术社区  · 7 年前

    我有一个集合列表,希望向其中添加一个集合。我的假设是我必须使用 :: operator .

    我的代码:

    // attribute_sets is a tuple (String, Set[String])
    
    val listsOfSets: List[Set[String]] = attribute_sets
          .foldLeft(List[Set[String]])((acc, attribute_set) => {
            acc  :: (attribute_set._2 + attribute_set._1)
          })
    

    Intellij表示存在类型不匹配( expected String, actual Set[String] )尝试添加到 acc .

    2 回复  |  直到 7 年前
        1
  •  1
  •   Roberto Bonvallet    7 年前

    你可以使用 :: 仅在列表开头添加元素:

    x :: list
    

    要在列表末尾添加某些内容,必须使用 :+ 操作员:

    list :+ x
    
        2
  •  1
  •   C4stor    7 年前

    类型 attribute_set._2 + attribute_set._1 String ,因为 + 使用的操作是 .

    因此 :: 操作无法解析,因为它用于连接集,而不是向集添加字符串。

    所以你要么改变 + 或者 :: 运算符取决于您期望的实际结果。

    推荐文章