'Type inference in ZIO giving Any in for comprehension

So I have written a method to count the number of lines in a file in ZIO.

def lines(file: String): Task[Long] = {
    def countLines(reader: BufferedReader): Task[Long] = Task.effect(reader.lines().count())
    def releaseReader(reader: BufferedReader): UIO[Unit] = Task.effectTotal(reader.close())
    def acquireReader(file: String): Task[BufferedReader] = Task.effect(new BufferedReader(new FileReader(file), 2048))

    Task.bracket(acquireReader(file), releaseReader, countLines)
  }

Now inside my run method when I try to extract the result like this:

for {
      lines <- linesV3("src/main/scala/FileIO.scala") //Type of lines showing as Any
      _ <- putStrLn(lines.toString) //This line throws error as it cannot convert Any to String
    }

The type of lines is coming as Any instead of Long. Why is this so? If I use flatMap then the type is inferred correctly.



Solution 1:[1]

so the solution was fairly similar. As soon as I add a yield after the for comprehension the type inference starts working correctly

for {
  lines <- linesV3("src/main/scala/FileIO.scala")
  _ <- putStrLn(lines.toString)
} yield ()

The toString method is required because putStrLn accepts only String parameters.

Solution 2:[2]

There's no problem with the code you posted here. The issue must be arising from somewhere else in your program. Maybe you are missing the yield after the for comprehension. I don't know if that is a copying error.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prakhar Singh
Solution 2 Navid Jalali