Scala 3 Significant Indentation Woes: Sample

| 1 minute | Comments

Here's a fairly straightforward Scala 3 sample, using significant indentation. Can you spot the compilation error?

//> using scala "3.3.0"

def sequence[A](list: List[Option[A]]): Option[List[A]] =
  list.foldLeft(Option(List.newBuilder[A])):
    (acc, a) =>
      acc.flatMap: xs =>
        a.map: x =>
          xs.addOne(x)
    .map(_.result())

Here’s the compilation error:

[error] ./sample.scala:9:10
[error] Found:    List[A]
[error] Required: scala.collection.mutable.Builder[A, List[A]]
[error]     .map(_.result())
[error]          ^^^^^^^^^^
Error compiling project (Scala 3.3.0, JVM)
Compilation failed

Here’s the corrected code:

//> using scala "3.3.0"

def sequence[A](list: List[Option[A]]): Option[List[A]] =
  list.foldLeft(Option(List.newBuilder[A])):
    (acc, a) =>
      acc.flatMap: xs =>
        a.map: x =>
          xs.addOne(x)
  .map(_.result())

FYI, this cannot happen in Python, because Python does not allow breaking expressions on multiple lines like that:

class MyList:
  def __init__(self, list):
    self.list = list
  def map(self, f):
    return MyList([f(x) for x in self.list])

# Doesn't parse
MyList([1, 2, 3])
  .map(lambda x: x + 1)

The error is:

  File "/tmp/sample.py", line 9
    .map(lambda x: x + 1)
IndentationError: unexpected indent

Maybe no indentation?

# Doesn't parse
MyList([1, 2, 3])
.map(lambda x: x + 1)
  File "/tmp/sample.py", line 9
    .map(lambda x: x + 1)
    ^
SyntaxError: invalid syntax

Yikes! What Python does is to make expressions unambiguous by requiring the escaping of line endings via a backslash:

MyList([1, 2, 3]) \
  .map(lambda x: x + 1)

Scala’s syntax keeps being compared with Python’s, however, they couldn’t be more different, as Python has had a very strict policy to avoid ambiguity, and even rejected multi-line lambdas for this reason.

I’m also begining to feel that 2 spaces for indentation are not enough 🙊

| Written by