我是Scala的新手,作为主题
package edu.luc.cs.cs372.echo
package main
object Main extends App {
val lines = scala.io.Source.stdin.getLines
val words = lines.flatMap(_.split("\\W+"))
val list2 = words.groupBy(_.length).mapValues(_.length)
val vectorOfLengths = (1 to list2.keys.max).map(length =>list2.getOrElse(length, 0))
for ((count, length) <- vectorOfLengths.zipWithIndex)
println(f"${length+1}: ${"#" * count}")
此处引发错误:
Error:(7, 21) value groupBy is not a member of Iterator[String]
val list2 = words.groupBy(_.length).mapValues(_.length)
^
Error:(9, 43) Cannot construct a collection of type That with elements of type (A1, Int) based on a collection of type scala.collection.immutable.IndexedSeq[Nothing].
for ((count, length) <- vectorOfLengths.zipWithIndex)
^
如何解决此问题?
答案 0 :(得分:0)
words
是Iterator
,groupBy
类上没有Iterator
方法,因此您必须将迭代器转换为其他方法:
words.toVector.groupBy(_.length)