我有以下简单的代码
private def tt(l:Seq[Int]):Seq[Future[Unit]] = {
val aa = l.map(_=>Future.successful(()))
aa
}
我很容易理解我正在返回 Future[Unit] type corresponding to each element of my sequence "l" that is passed to method tt.
很容易说 "aa"
的类型是 Seq[Future[Unit]]
. 我无法理解的是,当我的"l",序列长度为零时, Map 永远不会被执行,为什么以及如何我能够获得Seq [Future [Unit]]因为我已经明确地放了返回类型和明显scala很高兴,无论是什么"l"即使是空的,“aa”仍将导致Seq [Future [Unit]] . 但我不明白为什么
1 回答
以上陈述不正确 .
map
,当在空序列上调用时,执行:在空序列上调用map
返回空序列 .将空
Seq
传递给tt
时,返回类型确实是Seq[Future[Unit]]
. 返回的是一个空的Seq[Future[Unit]]
:在上面的代码中,
map
在l
上执行,即使l
为空 .在任何类型的空
Seq
上调用map
都是一样的 . 例如,要将Seq[String]
转换为Seq[Int]
:在空
Seq[String]
上调用.map(_.toInt)
的结果为空Seq[Int]
.