scala - 从理解转换为地图的问题
问题描述
我正在尝试将 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方式的建议将不胜感激。
解决方案
错误消息中的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) }
推荐阅读
- javascript - 如何使用 Nodejs 后端将文件上传到 MySQL 数据库并显示照片
- docker - 从 minio 服务器获取对象而不将额外数据传递到 URL
- sql-server - 当作业在 10 分钟内仅失败五次时寻找作业通知
- html - How to make smooth scrolling in CSS?
- razor-pages - 编译器不再生成 Views 程序集并且页面名称被混淆
- c# - 从 UWP 访问 LocalDB 时出错:LocalDB 实例 API 方法调用内部发生意外错误
- vue.js - 我无法在 vuejs 中安装包
- angular - Angular 11 应用程序无法在 Tizen 上运行(三星电视)
- python - 如何获取小数点前后的数字?
- typescript - 打字稿 CLI 运行器