Suga Raj
Suga Raj

Reputation: 551

Scala- zip with futures

Below is the code which i am trying to understand:

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)

}

The Problem:

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

Here if you notice, i am not using a "." before zip and just giving a space. I guess that . and space both works in same way and also validated it some stack overflow questions. the above expression before applying a map will result me a Future[(List[String],List[String])]. so when i say

.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.

what might be the reason?

Upvotes: 4

Views: 1138

Answers (1)

Andrei T.
Andrei T.

Reputation: 2480

When you omit the space (by replacing the .) you have to also omit the parentheses, otherwise the compiler will consider whatever comes after as part of the initial expression - in your case the map(x => x.tail) will be applied to the Future{List("Tim", "Joe", "Fin")}.

A simple example can be observed here:

val y = 3 to(5).toDouble

The #toDouble is actually applied to the number 5. If you try to use the range defined methods, it won't work.

Going back to your code, if you remove the . before the tail call, you will get the expected compile error:

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

Upvotes: 6

Related Questions