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.

Feedback welcome!

// edit
Since there have been no more comments for 2 weeks and the feedback has been universally positive, I’ve now submitted this to the committee.

18 Likes

Yes please!

2 Likes

I like this for while loops. The motivation for doing it in if/else isn’t as good, besides symmetry.

A situation I have encountered with if where this would be an improvement is when I have a declaration I only want in an else, but want to use in multiple else clauses. Presently I need to add a nesting level:

if x then
  ???
else
  val y = ???
  if y && z then ???
  else if y then ???
  else ???

After:

if x then
  ???
else if
  val y = ???
  y && z
then ???
else if y then ???
else ???

I agree it’s not as useful for if as it is for while, but I’m still pretty sure it’s the right thing to do both together.

  • it still has utility: it can help keep variable scope smaller, which is always a good thing and the stated reason why other languages like C++ allow this (albeit in a more limited form)
  • it’s unlikely to break anything, so there isn’t much reason not to
  • it’s essentially impossible to explain why the two would behave differently
3 Likes

Agreed. I do think adding an example like mine to the SIP would give the if version better justification though. Maybe event directly address that it isn’t quite as important for if but the lacks of symmetry would end up being baffling.

Did you consider if in case?

1 Like

+1 !

3 Likes

This is an appealing proposal with virtually no downside I can see.

(The SIP seems to address any compatibility/migration concerns adequately.)

1 Like

Both parts of the proposal also mirror what for comprehensions already do: definitions in the head of a for, whether generators or value definitions such as y = f(x), are visible in its body.

Since for-comprehensions allow assignments without val, could while and if conditions also omit val?

1 Like

I don’t think that would be wise, since otherwise it would look like variable assignment
(for clauses are not regular blocks, and there the -> surrounding syntax makes = being a declaration less weird)

4 Likes

output

Thanks, I’ve added that as a motivating example to the SIP.

Yes, but it can’t be implemented in the rather straight-forward manner that the current proposal can. Also, the experimental subCases feature in Scala 3.9 already allows binding variables in case ifs, so maybe it’s time to push that forward in order to close that gap.

maybe we could also support refutable pattern matching, like in rust/swift (possibly as separate SIP)?

something like:

if case Some(x) = opt then // or `if val Some(x) = opt`, symmetric with value notation
  use(x) // x in scope 

if case Some(x) = opt && something(x) then
  use(x)

and:

while case Some(line) = it.nextOption() do 
  process(line)

which expands on already mentioned in improvement-proposals/content/condition-bindings.md at condition-bindings · mberndt123/improvement-proposals · GitHub “Related work” section:
Pattern bindings in the condition. Rust has if let and while let , and since Rust 1.88 let chains such as if let Some(x) = a && x > 0 . Swift has if let , while let and guard let . Java (o instanceof String s , JEP 394) and C# (out var , patterns) bind variables in conditions as well.

1 Like

It should be pretty simple to define a macro that takes a match expression and evaluates it repeatedly until it doesn’t match anymore.
Then you can write something like

whileMatches:
  it.nextOption() match
    case Some(x) => process(line)

Now granted, your proposed syntax also allows more advanced cases, like

while case Some(line) = it.nextOption() && case Some(line2) = it.nextOption() do
  process(line, line2)

But with the experimental Match Expressions with Sub Cases, those cases are covered too. So I think it’s not worth adding a language feature for this, but perhaps you can propose to add a suitable macro to the standard library. A large reason I made this proposal is that it doesn’t require new syntax but just makes existing syntax more useful.

already easily doable:

for x <- opt if something(x)

Even more complex cases work if you wrap in Some, for example:

for case JsonString(str) <- Some(jsValue) if str.nonEmpty

if we add support case-assignment, it could become (pretty much what if-let is):

for case JsonString(str) = jsValue if str.nonEmpty

whileMatches already exists as a while statement without a body.

while {
   // repeat while this is true
} do ()

Yes, but then you need an exhaustive pattern match and return true or false, which is a little bit of boilerplate. A macro can take are of that and make things look a little nicer.