St.Antario
St.Antario

Reputation: 27375

Type inference in Scala. How does it work in this case?

I'm experementing with fs2.Stream and faced some misunderstanding about type inference. Let's say that we have the following code:

import cats.effect.IO

val ios = IO(List(1, 2, 3))
val s: fs2.Stream[IO, Int] = fs2.Stream.eval(ios).flatMap(l => 
  fs2.Stream.emits(l)
) //compiles OK, but why?

And it compiles fine. But I don't understand why it the type is fs2.Stream[IO, Int]? Here is the signature:

def flatMap[F2[x] >: F[x], O2](f: O => Stream[F2, O2]): Stream[F2, O2] // F = IO?
def emits[F[x] >: Pure[x], O](os: Seq[O]): Stream[F, O]

So emits returns a fs2.Stream[Pure, Int], but flatMap of fs2.Stream[IO, Int] wants F2[x] >: F[x] where F = IO, but F2 = Pure. Pure[x] >: IO[x] is not correct...

How does it work?

Upvotes: 0

Views: 86

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

So emits returns a fs2.Stream[Pure, Int]

No, it doesn't.

  1. Given expected type of s, the expected type of l => fs2.Stream.emits(l) is List[Int] => fs2.Stream[IO, Int], so

  2. the expected type of fs2.Stream.emits(l) is fs2.Stream[IO, Int], so

  3. F in the signature of emits is inferred to be IO.

Upvotes: 2

Related Questions