scala - 不理解此 Scala 代码的结构(或语法含义)

标签 scala

我是 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/

相关文章:

scala - HList 上的映射因 Scala 和 Shapeless 中的泛型类型的子类型而失败

scala-redis 需要 sbt 0.10.1(其他版本不工作)——这正常吗?

scala - 从 Scala REPL 打印当前日期的最简单/最简单的方法?

scala - 映射选项中的键/值[映射]

java - 如何实现可变元素数组

java - Zeppelin 中的 IndexOutOfBounds 错误

java - 在 Play 中使用@select! Framework 2.3模板和Java

scala - 函数不接受任何参数

scala - 覆盖 java.util.HashMap.get() 方法

scala - 为什么 sbt 找不到我的本地包