scala-mapValues转换为理解转换错误

时间:2019-05-16 15:19:57

标签: scala

我正在尝试将转换后的map()转换为具有理解力,但会出现错误

println("Citi names concatenated by country code")
println("Method1")
orec.groupBy( x => x.ccode ).mapValues( x => x.map( a => a.cityname).mkString("[",",","]")).take(5).foreach(println)
println("Method2")

下面的代码抛出错误

var i = 0
for{
  (key,value) <- orec.groupBy( x => x.ccode )
  cities = value.map( a=> a.cityname)
  cities2 = cities.mkString("[",",","]")
  i=i+1
  if(i<5) {
    _ = println(key + "->" + cities2)
  }
} yield ()

错误消息:

Error:(49, 10) recursive value i needs type
      i=i+1
Error:(50, 11) value < is not a member of Any
      if(i<5)

如何使用不变方法解决此问题?不过,我仍然不知道如何将map()版本中的take(5)转换为理解。

2 个答案:

答案 0 :(得分:1)

要替换take(5),可以在索引上使用if来生成索引,可以使用zipWithIndex

如果要在Scala中增加var,则需要指定var的类型。 (此处Int

这就是您可能正在寻找的代码

case class City(ccode: String, cityname: String)
val orec: Seq[City] = Seq(City("fr", "paris"), City("fr", "lille"), City("fr", "bordeaux"), City("en", "london"), City("be", "gantt"), City("de", "berlin"), City("austria", "vienna"), City("us", "ny"))

for (((key, value), index) <- orec.groupBy( x => x.ccode ).zipWithIndex){
  val cities = value.map( a=> a.cityname)
  val cities2 = cities.mkString("[",",","]")
  if (index<5)
    println(key + "->" + cities2)
}

答案 1 :(得分:1)

您误将“中游分配”分配给您的var i

以前需要val的语法:

scala> for (i <- List(42) ; val j = i + 1) yield j
                                  ^
       warning: `val` keyword in for comprehension is deprecated: instead, bind the value without `val`
res3: List[Int] = List(43)

scala> val i = i + 1
               ^
       error: recursive value i needs type

保留take是更常见的做法,但在其他答案上却有所改进:

scala> for {
     | ((key, value), index) <- orec.groupBy( x => x.ccode ).zipWithIndex
     | cities2 = value.map( a=> a.cityname).mkString("[",",","]")
     | if index < 5
     | } println(key + "->" + cities2)
fr->[paris,lille,bordeaux]
us->[ny]
de->[berlin]
en->[london]
be->[gantt]

scala> for {
     | (key, value) <- orec.groupBy(_.ccode)
     | } yield (key, value.map(_.cityname).mkString("[",",","]"))
res4: scala.collection.immutable.Map[String,String] = HashMap(fr -> [paris,lille,bordeaux], us -> [ny], de -> [berlin], en -> [london], be -> [gantt], austria -> [vienna])

scala> .take(5).foreach { case (k,v) => println(s"$k -> $v") }
fr -> [paris,lille,bordeaux]
us -> [ny]
de -> [berlin]
en -> [london]
be -> [gantt]

scala> val it = orec.groupBy(_.ccode).mapValues(_.map(_.cityname).mkString("[",",","]")).iterator
                                      ^
       warning: method mapValues in trait MapOps is deprecated (since 2.13.0): Use .view.mapValues(f). A future version will include a strict version of this method (for now, .view.mapValues(f).toMap).
it: Iterator[(String, String)] = <iterator>

scala> for ((k, v) <- it.take(5)) println(s"$k -> $v")
fr -> [paris,lille,bordeaux]
us -> [ny]
de -> [berlin]
en -> [london]
be -> [gantt]