0
我注意到了有关的地图,flatMap和未来几个有趣的行为,但我无法理解是什么原因造成这种现象有趣的地图和flatMap观察 - 未来,斯卡拉
//I have 3 Future objects.
object ConcurrencyExample extends App {
val time = System.currentTimeMillis()
val future1 = Future{println("future1");1}
val future2 = Future{println("future2");2}
val future3 = Future{println("future3");3}
//I want to add 1,2 and 3. I can do it using flatMap
val result = future1 flatMap (f1=> future2.flatMap(f2 => future3.map(f3=> f3+f2+f1)))
result onComplete{
case Success(v)=>println("result is "+v)
case Failure(e) =>println("failed result:"+e)
}
Thread.sleep(1000)
}
结果
future2
future1
future3
result is 6
如果我将上面的代码更改为map,我会得到一个空的List()。我无法跟踪这个空列表来自哪里?
val result = future1 map (f1=> future2.map(f2 => future3.map(f3=> f3+f2+f1)))
结果
future3
future2
future1
result is List()
如果我只用两个未来的对象和地图,我获得成功(3),而不是一个空列表()
val result = future1 map (f1=> future2.map(f2 => f2+f1))
结果
future3
future2
future1
result is Success(3)
如果您升级到最新版本的Scala 2.11或直接升级到Scala 2.12.x,那么您会看到比“List()”多的字符串表示形式 –
有关Viktor在https://问题上的说明的详细信息.scala-lang.org /浏览/ SI-9488。请注意,Scala 2.11.9还没有发布,所以目前还没有正式的2.11版本(2.11 nightlies有)。 –