Search code examples
scala

What does this Scala syntax mean ("= something" after a method)?


Two examples from the Scala's blog:

def canFail(input: String): Try[List[String]] = Try:
  someComputation(input).flatMap: res =>
    val partial = moreComputation(res)
    andEvenMore(partial)

and this one:

import util.boundary, boundary.break

def sumOfRoots(numbers: List[Double]): Option[Double] = boundary:
  val roots = numbers.map: n =>
    println(s" * calculating square root for $n*")
    if n >= 0 then Math.sqrt(n) else break(None)
  Some(roots.sum)

In the first example the method returns Try[List[String]]. But what is = Try? And in the second example, = boundary... What is it?


Solution

  • Your first example could be rewritten with braces syntax as the following which hopefully is more clear:

    def canFail(input: String): Try[List[String]] = {
      Try {
        someComputation(input).flatMap { res =>
          val partial = moreComputation(res)
          andEvenMore(partial)
        }
      }
    }
    

    = is just the start of method body definition.

    In my code above, the first braces are not necessary. Same could be written:

    def canFail(input: String): Try[List[String]] = Try {
      someComputation(input).flatMap { res =>
        val partial = moreComputation(res)
        andEvenMore(partial)
      }
    }
    

    And then, if you changes braces for the indentation syntax, you get your first code example.


    As for Try { ... }, it's syntactic sugar for Try.apply { ... }, itself the same as Try.apply({ ... }).