ASK
ASK

Reputation: 11

Inteliji showing ```_ <- ``` error for scala zio operator

enter image description here enter image description here

<- operator is working fine in basic for loop of zio but with the zip operator IntelliJ showing error.

Solution to solve the IntelliJ issue

Upvotes: 0

Views: 98

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27595

It's not IntelliJ, it's Scala.

This:

for {
  (a, b) <- foo
} yield ()

Does NOT translate to

foo.flatMap { case (a, b) =>
  ()
}

It translates to:

foo.withFilter {
  case (a, b) => true
  case _      => false
}.map {
  case (a, b) =>
    ()
}

By specification pattern matching in for-comprehension (here (a, b) <- sth) is not checked by compiler for exhaustiveness, so instead it uses .withFilter to filter out all values which cannot be pattern-matched with it, before using .map/.flatMap/.foreach with case to process them.

ZIO does not define .withFiler which is why compiler (and IntelliJ) complains. Because you have uncommented invalid code in 2 of your examples. In fact, many structures don't have it, since it doesn't make any sense for them to have some "default" way of filtering, and how would it work securely (e.g. Future fails when you filter out its value, giving you some unhelpful exception message. Failing manually with Future.failure inside .flatMap would allow you to give it some meaningful error if you have to).

If you want to change this behavior use better-monadic-for compiler plugin. Or Scala 3 with -source:future flag. Alternatively, you can work around this issue with:

for {
  _ <- Console.printLine("test")
  result <- Random.nextUUID zip Console.readLine
  (uuid, name) = result
} yield ()

since = creates just a normal val and it doesn't get in your way of creating unchecked match and extraction.

Upvotes: 3

Related Questions