斯卡拉方法=特质{...}的含义 [英] Scala method = trait { ... } meaning

查看:118
本文介绍了斯卡拉方法=特质{...}的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图同时学习Scala和Play框架。 Scala在我看来喜欢它有很多非常酷的想法,但我的一个挫折就是试图理解方法/函数/ lambdas /匿名函数/等的所有不同语法。



所以我有我的主要应用程序控制器如此:

 对象应用程序扩展控制器{
def index = Action {
Ok(views.html.index(Your new application is ready。))
}
}

这告诉我有一个singleton Application ,它有一个方法, index ,返回什么类型?我希望 index 的定义更像:

  def index (req:Request):Result = {...} 

查看Play Framework的文档,就好像 Action 是一个特征,它将请求转换为结果,因为我很难理解这行代码是什么意思:

  def index =动作{...} 

我来自Java背景,所以我不知道这是什么意思? (这种说法感觉像是在说'方法索引= [一些接口动作],这对我来说没有意义;看起来好像有些美好的事情发生了,但这对我来说是神奇的,而我在我的代码中感到不自然);)

解决方案

当你像对待一个函数一样调用一个对象时,调用应用。即:

  foo(bar)

被翻译成

  foo.apply(bar)
index
中,您正在调用 Action $ b> / code>对象就好像它是一个函数,这意味着你实际上调用了 Action.apply



返回类型 index 被忽略,因为编译器可以推断它是 Action.apply的返回类型(我猜的名字是 Unit )。


I'm trying to learn Scala and the Play Framework at the same time. Scala looks to me like it has a lot of really cool ideas, but one of my frustrations is trying to understand all of the different syntaxes for methods/functions/lambdas/anonymous functions/etc.

So I have my main application controller like so:

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

This tells me I have a singleton Application that has one method, index, that returns what type?? I was expecting index to have a definition more like:

def index(req: Request) : Result = { ... }

Looking at Play Framework's documentation, it looks as though Action is a trait, that transforms a request to a result, by I'm having a hard time understanding what this line is saying:

def index = Action { ... }

I come from a Java background, so I don't know what this is saying? (this statement feels like it's saying "method index = [some interface Action]", which doesn't make sense to me; it seems something beautiful is happening, but it is magic to me, and I feel uneasy with magic in my code ;))

解决方案

When you invoke an object as if it were a function, that's translated into a call to apply. I.e.:

foo(bar)

is translated into

foo.apply(bar)

So, inside index you are calling the Action object as if it were a function, which means you are actually calling Action.apply.

The return type of index is omitted because the compiler can infer it to be the return type of Action.apply (which I guess from the name is Unit).

这篇关于斯卡拉方法=特质{...}的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆