Search code examples
scalascala-3scalafmt

How to lint and format newline after `yield` in Scala 3?


How can I restrict the formatting of a Scala-3 project, so that newline is required after yield keyword?

For examples, I want this code to be rejected by linter/formatter

for
  a <- Some(1)
  b <- Some(2)
yield a + b

And the correct one would be:

for
  a <- Some(1)
  b <- Some(2)
yield
  a + b

Solution

  • The tool usually employed to format Scala source code is scalafmt.

    By default, newlines after yield are removed, but you can preserve them by setting newlines.avoidAfterYield to false in your .scalafmt.conf.

    Note that while this gets close to what you are looking for, it doesn't go all the way, as this prevents the removal of newlines after a yield but doesn't automatically add one.

    If you feel strongly that this is a behavior that should be part of scalafmt, you can probably suggest it to the maintainer and perhaps even contribute yourself. For reference, this is the PR that introduced newlines.avoidAfterYield.