Pre-SIP: Bindings in while and if conditions

Hi everybody,

Many loops need to compute something before they can decide whether to continue. This is the classic loop-and-a-half problem. In Scala today, that means duplicating code, using a var with a dummy initial value, or using boundary/break.

Scala 3 already has the syntax for a clean solution, because the condition of a while can be a block. The only problem is that definitions in that block aren’t visible in the body:

while
  val line = in.readLine()
  line != null
do
  process(line) // today: Not found: line

I propose making them visible. if expressions get the same rule, so definitions in the condition are visible in then and else.

The change is only source-incompatible when a definition in the condition shadows an outer name that the body uses. That should be rare, and a migration warning will flag it.

Feedback welcome!

6 Likes

Yes please!