Scala 从理解到映射的转换问题

Scala 从理解到映射的转换问题,scala,for-comprehension,Scala,For Comprehension,我试图将用于理解的Scala转换为使用map,我遇到了一个问题 用于说明,考虑下面的转换,如预期的那样工作。< /P> 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.coll

我试图将用于理解的Scala
转换为使用
map
,我遇到了一个问题

用于说明,考虑下面的转换,如预期的那样工作。< /P>

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)
错误消息说我需要提供一个函数,该函数接受
Int
并返回“something”(不确定
代表什么)

因此,我可以看出存在不匹配。但是我如何将我希望发生的事情——对
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实现这一点的方法将不胜感激。

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

scala> 0 to 10 map { Random.nextInt(10) }
<console>:13: error: type mismatch;
 found   : Int
 required: Int => ?
       0 to 10 map { Random.nextInt(10) }
                                   ^
0 to 10 map { i => Random.nextInt(10) }
也可以显式忽略该参数:

0 to 10 map { _ => Random.nextInt(10) }
或者,更好的方法是使用
填充

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

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

0 to 10 map { i => Random.nextInt(10) }
也可以显式忽略该参数:

0 to 10 map { _ => Random.nextInt(10) }
或者,更好的方法是使用
填充

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