gpt4 book ai didi

scala - 理解 Scala block

转载 作者:行者123 更新时间:2023-12-03 12:11:10 25 4
gpt4 key购买 nike

对于我所知道的一些微不足道的事情,我很难找到具体的答案。我想了解块在 Scala 中是如何工作的。我来自 java/ruby 背景,scala 似乎有一种完全不同的使用块的方式。

以下代码来自 Play! Framework website .我想了解什么行动是语义。它是接受块的对象还是函数,或者两者都不是。

object Application extends Controller {

def index = Action {
Ok(views.html.index("Your new application is ready."))
}

}

如果它是一个函数,那么它可能是以下内容的语法糖(在这种情况下,scala 如何在后台传递块):
  def index = Action({
Ok(views.html.index("Your new application is ready."))
})

或者是我不知道的一些 Scala 语法。

任何对 Scala 源代码的引用都会帮助我理解这是如何在幕后工作的。

最佳答案

您最好将 Scala 块视为 java 匿名类(例如 Guava 函数)而不是 ruby​​ 块。实际上,如果您反编译 Scala 代码,您会看到或多或少相同的代码( taken from Guava examples ):

Function<String, Integer> lengthFunction = new Function<String, Integer>() {
public Integer apply(String string) {
return string.length();
}
};

不同之处在于 scala 提供了很多语法糖,并允许您将上面的代码编写为:
val lengthFunction = { string: String => string.length }

至于具体的 Action 示例:
def index = Action({
Ok(views.html.index("Your new application is ready."))
})

这里 Action 可能是带有 apply 方法的对象。另一种scala糖:语言允许你写 Foo(bar)和平均值 Foo.apply(bar) .接下来, you can drop round braces when your call isn't ambiguous ,所以是的,它实际上是一个被调用的方法,如:
def index = Action({
Ok(views.html.index("Your new application is ready."))
})

并有这样的东西作为签名:
object Action {
def apply(block: => Result) = ???
}

正如@yan 已经说过的,这是 scala 的表达方式,嘿,我是一个函数,它接受另一个产生 Result 的函数

脱糖调用看起来像
def index = Action.apply(new AbstractFunction[Result] {
def apply() = Ok.apply(views.html.index.apply("..."))
})

关于scala - 理解 Scala block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19007611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com