英文:
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({ ... })
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论