curiousengineer
curiousengineer

Reputation: 2625

map on a scala List/Seq

I have the below simple code

private def tt(l:Seq[Int]):Seq[Future[Unit]] = {
    val aa = l.map(_=>Future.successful(()))
    aa
  }

I can easily grasp the fact that I am returning Future[Unit] type corresponding to each element of my sequence "l" that is passed to method tt. It is easy to say that "aa" is of type Seq[Future[Unit]] as a consequence. What I am unable to get my head around is that when my "l", the sequence is of length zero, map will never be executed, why and how even then am I able to get Seq[Future[Unit]]because I have explicitly put the return type and clearly scala is happy that no matter what is "l" even if empty, "aa' will still result with Seq[Future[Unit]]. But I fail to get why

Upvotes: 1

Views: 14104

Answers (1)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

...when my "l", the sequence is of length zero, map will never be executed....

The above statement is incorrect. map, when called on an empty sequence, is executed: calling map on an empty sequence returns an empty sequence.

When you pass an empty Seq to tt, the return type is indeed Seq[Future[Unit]]. What is returned is a Seq[Future[Unit]] that is empty:

scala> def tt(l:Seq[Int]):Seq[Future[Unit]] = {
 |     val aa = l.map(_=>Future.successful(()))
 |     aa
 |   }
tt: (l: Seq[Int])Seq[scala.concurrent.Future[Unit]]

scala> tt(Seq())
res0: Seq[scala.concurrent.Future[Unit]] = List()

In the above code, map is executed on l, even when l is empty.

It's the same with calling map on an empty Seq of any type. For example, to convert a Seq[String] to a Seq[Int]:

scala> Seq[String]().map(_.toInt)
res2: Seq[Int] = List()

The result of calling .map(_.toInt) on an empty Seq[String] is an empty Seq[Int].

Upvotes: 5

Related Questions