Scala- 带期货的 zip

Scala- zip with futures

下面是我试图理解的代码:

object Tryouts extends App{
    val studentIds= Future{
        List("s1","s2","s3")
    }
    val details = studentIds zip(Future{List("Tim","Joe","Fin")}).map(x=>x.tail)
    details.foreach(println)
    Thread.sleep(1000)

}

问题:

val details = studentIds zip(Future{List("Tim","Joe","Fin")}).map(x=>x.tail)

如果你注意到了,我没有使用“.”。在 zip 之前,只给出一个 space。我猜是 。和 space 都以相同的方式工作,并且还验证了一些堆栈溢出问题。应用地图之前的上述表达式将导致 Future[(List[String],List[String])]。所以当我说

.map(x=x.tail) should show compilation error in IDE because tail operation can be applied only on list and not for tuple. But it is actually executing successfully.

The same statement when executed with "." before zip function like this:

val details = studentIds.zip(Future{List("Tim","Joe","Fin")}).map(x=>x.tail) the map(x=>x.tail) gives error.

可能是什么原因?

当您省略 space(通过替换 .)时,您还必须省略括号,否则编译器会将后面的内容视为初始表达式的一部分 - 在您的情况下map(x => x.tail) 将应用于 Future{List("Tim", "Joe", "Fin")}

这里可以看到一个简单的例子:

val y = 3 to(5).toDouble

#toDouble实际上是应用到数字5上的,如果你尝试使用范围定义的方法,它是行不通的。

回到你的代码,如果你在尾调用之前删除 .,你将得到预期的编译错误:

val details = ids zip Future.successful(List("Tim", "Joe", "Fin")) map (_.tail)
// compile error: "Cannot resolve symbol tail"