Skip to content

Latest commit

 

History

History
102 lines (86 loc) · 2.43 KB

2023-06-06-scala-3-significant-indentation-woes-sample.md

File metadata and controls

102 lines (86 loc) · 2.43 KB
title image image_hide_in_post date last_modified_at tags description
Scala 3 Significant Indentation Woes: Sample
/assets/media/articles/2023-scala-indentation-woes.png
true
2023-06-06 14:48:10 +0300
2023-06-07 07:52:16 +0300
Programming
Python
Scala
Scala 3
Here's a fairly straightforward Scala 3 sample, using significant indentation. Can you spot the compilation error?

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 🙊