这个Scala语法表示在一个方法之后的 “= something” 是指方法的返回值类型。

huangapple go评论74阅读模式
英文:

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

问题

以下是翻译好的部分:

第一个例子中,该方法返回Try[List[String]]。但是 = Try 是什么?

第二个例子中,= boundary... 这是什么?

英文:

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?

答案1

得分: 3

你的第一个示例可以使用大括号语法重写,如下所示,这样可能更清晰:

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

= 只是方法主体定义的开始。

在我上面的代码中,第一个大括号是不必要的。可以写成:

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

然后,如果将大括号更改为缩进语法,就会得到你的第一个代码示例。


至于 Try { ... },它是 Try.apply { ... } 的语法糖,本身与 Try.apply({ ... }) 相同。

英文:

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({ ... }).

huangapple
  • 本文由 发表于 2023年8月4日 02:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定