我是 Scala 初学者,需要了解以下语法。 代码结构为
// val context = ...
// val future = Future {...} (context)
我不明白这是什么意思。
val context = ExecutionContext.fromExecutorService(...)
val future = Future {
breakable {
while (true) {
try {
handle(something)
}
catch {
case _: InterruptedException =>
}
}
}
} (context) // what does this syntanx mean? Future {...} (val)
右花括号后面的这个(上下文)是什么???
最佳答案
在Scala中,您可以定义具有多个参数组的函数。这样做的主要目的是使用 currying .
def foo(bar: Int)(bar2: Long) = bar + bar2
然后 Scala 允许您通过以下方式调用此函数:
@ foo{1}{2}
res1: Long = 3L
@ foo{1}(2)
res2: Long = 3L
@ foo(1)(2)
res3: Long = 3L
@ foo(1){2}
res4: Long = 3L
因此您可以选择使用 {}
或 ()
。粗略地说,{}
允许使用多个表达式,而 ()
则不允许。此外,{}
仅适用于单个参数,因此如果您有两个或多个参数,则只能使用 ()
。
@ foo(1){println("hi");2}
hi
res7: Long = 3L
@ foo(1)(println("hi");2)
SyntaxError: found ";2)", expected "," | ")" at index 20
foo(1)(println("hi");2)
回到你的问题,Future.apply
(这就是你上面使用的)的定义类似于foo
。它使用柯里化(Currying)函数语法接受两个参数。
关于scala - 不理解此 Scala 代码的结构(或语法含义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971283/