-Ywarn-unused in for comprehension

-Ywarn-unused does not seem to issue any warnings for unused1 and unused2 in the following code snippet:

for {
  unused1 <- Some(())
  unused2 = ""
} yield {
  println("hello world")
}

It seems to me like it ought to warn for both variables in this case. Could -Ywarn-unused be modified to raise a warning in this case (perhaps with a new unused warning category of for)?

I’d be happy to attempt a PR myself but I just want to confirm first that this would be useful and that there are no issues conceptually with issuing warnings in the following case.

2 Likes

unused2 could be removed but unused1 could only be changed to _.

Currently, the warning examines trees, rather than tracking definitions and usages (as happens for unused imports). That might have to change to improve effectiveness.

The warnings around for comprehensions has been tweaked a bit. You can check the bug list.

Your example actually looks like this:

scala 2.13.0-M4> for (i <- Some(42); j = 5) yield 17 // print

scala.Some.apply[Int](42).map[(Int, Int)](((i: Int) => {
  val j = 5;
  scala.Tuple2.apply[Int, Int](i, j)
})).map[Int](((x$1: (Int, Int)) => (x$1: @scala.unchecked) match {
  case scala.Tuple2((i @ _), (j @ _)) => 17
})) // : Option[Int]

It might be possible to track identifiers introduced in a for comprehension, but the syntactic rewrite happens early, so if there is shadowing, you wouldn’t get much support. For example,

for (i <- Some(42); j = 5) yield { val j = 17 ; j }

Edit: there is movement to change the desugaring, which might make any effort easier or harder or unnecessary.

1 Like

For current warnings in pattern, there is an escape hatch if you want an identifier:

scala 2.13.0-M4> 17 match { case i => 42 }
                                 ^
                 warning: pattern var i in value res5 is never used; `i@_' suppresses this warning
res5: Int = 42