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

如何获取Seq[String]而不是Seq[Any]?

  •  1
  • ScalaBoy  · 技术社区  · 6 年前

    我需要做以下转换和 columnNames 应该是 Seq[String] 然而,它总是 Seq[Any] . 我怎样才能解决这个任务?

    val cols = Seq("col1","col2")
    val columnNames: Seq[String] = cols ++ "col3"
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Raphael Roth    6 年前

    你应该做:

    val columnNames: Seq[String] = cols :+ "col3"
    

    val columnNames: Seq[String] = cols ++ Seq("col3")
    

    对你来说结果是 Seq[Any] 因为 Any String Char

        2
  •  1
  •   RAGHHURAAMM    6 年前

    ++ :+ +: 是要添加 element collection 收集 应始终与相邻 : 以及 要素 + 在里面 :+ collection :+ element element +: collection append prepend 要素 分别。所以 cols :+"col3" 会给我们预期的答案,因为 "col3" 将被视为 string element 添加到 cols .

    cols ++ "col3" String “第3列” List('c','o','l','3') 科尔斯 是字符串的集合。因此,生成的集合是 List[Any] ,因为它包含字符串和字符 字符串 Char Any 由编译器进行。

        3
  •  0
  •   james.bondu    6 年前

    val columnNames: Seq[String] = cols :+ "col3"

    :+ 是someVariable.next()返回的任何类型的方法。

    你在上课 Any