我试图将Scala for comprehension转换为使用map,但我遇到了一个问题。
为了说明这一点,请考虑下面的转换,该转换按预期工作。
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并返回"something“(不确定?代表什么)。
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方式的建议将不胜感激。
发布于 2019-01-02 06:09:59
错误消息中的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) }https://stackoverflow.com/questions/53999293
复制相似问题