首页 > 解决方案 > 从理解转换为地图的问题

问题描述

我正在尝试将 Scalafor comprehension转换为 usingmap并且遇到了问题。

为了说明,请考虑以下转换按预期工作。

scala> for (i <- 0 to 10) yield i * 2
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

scala> 0 to 10 map { _ * 2 }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20)

但是,以下不起作用。我犯了什么错误?

scala> import util.Random
import util.Random

scala> for (i <- 0 to 10) yield Random.nextInt(10)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 0, 7, 5, 9, 4, 6, 6, 6, 3, 0)

scala> 0 to 10 map { Random.nextInt(10) }
<console>:13: error: type mismatch;
 found   : Int
 required: Int => ?
       0 to 10 map { Random.nextInt(10) }
                                   ^

根本原因可能是我无法正确解读错误消息或修复原因。当我查看它的签名时,Random.nextInt它似乎正在返回一个Int.

scala> Random.nextInt
   def nextInt(n: Int): Int   def nextInt(): Int

错误消息是说我需要提供一个接受Int并返回“某物”的函数(不确定?代表什么)。

required: Int => ?

所以我可以看到有一个不匹配。但是我如何将我想要发生的事情——调用Random.nextInt(10)——转换为函数并将其传递给map

任何有助于理解下面的错误消息将不胜感激。

scala> 0 to 10 map { Random.nextInt(10) }
<console>:13: error: type mismatch;
 found   : Int
 required: Int => ?
       0 to 10 map { Random.nextInt(10) }
                                   ^

(编辑)

执行以下操作有所帮助。

scala> def foo(x: Int): Int = Random.nextInt(10)
foo: (x: Int)Int

scala> 0 to 10 map { foo }
res10: scala.collection.immutable.IndexedSeq[Int] = Vector(0, 2, 1, 7, 6, 5, 1, 6, 0, 7, 4)

但是对此的评论或推荐的Scala方式的建议将不胜感激。

标签: scalafor-comprehension

解决方案


错误消息中的Int => ?意味着编译器期望从Int某个其他类型(?)中看到一个函数。但Random.nextInt(10)它不是一个函数,它只是一个Int. 您必须采用整数参数:

0 to 10 map { i => Random.nextInt(10) }

您也可以显式忽略该参数:

0 to 10 map { _ => Random.nextInt(10) }

或者,更好的是,只需使用fill

Vector.fill(10){ Random.nextInt(10) }

推荐阅读