Home > Mobile >  Type inference in ZIO giving Any in for comprehension
Type inference in ZIO giving Any in for comprehension

Time:05-09

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related