Spark word count example : why error: value split is not a member of Char at the REPL?

Spark word count example : why error: value split is not a member of Char at the REPL?

从 Spark 示例 (https://spark.apache.org/examples.html) 中,代码如下所示:

    val file = spark.textFile("hdfs://...")
     val counts = file.flatMap(line => line.split(" "))
                 .map(word => (word, 1))
                 .reduceByKey(_ + _)

并在编译时工作。 但是,如果我在 Spark REPL 中尝试这个确切的代码:

scala> val lines = "abc def"
lines: String = abc def

scala> val words = lines.flatMap(_.split(" "))
<console>:12: error: **value split is not a member of Char**
       val words = lines.flatMap(_.split(" "))
                                   ^

什么给了??

谢谢 马特

file 可能是 Iterator[String] 或类似的东西。在您的代码中,lines 只是一个 String。没有迭代器。这意味着当您对 String 进行平面映射时,您将 String 视为集合,因此每个元素都是一个 CharChar 没有 split 作为方法(没有意义)。

如果你把它拆开一点..

val words = lines.flatMap(x => x.split(" "))
                          ^ this is a Char

您可以只拆分字符串本身。

val words = lines.split(" ")

lines 只是一个字符串。所以 flatmap 是 运行 针对字符序列。你需要使用 RDD

val rddYouCanUse = sc.parallelize(List("abc def"))