问题描述
以下控制器: package test
$ b $ class TestController {
static defaultAction =test
def test(){
rendertest
}
}
为什么用 def test(){
来定义 test
像 void test(){
?是不是 def
关键字仅用于脚本中的闭包或函数(即不在Groovy类中)?
var
,你可以把它想象成Java中的 Object
。 我认为使用 def
就像在做(JavaScript)一样
var test = function(){
alert(test);
}
而实际上它就像(Java)
public Object test(){
return someObject;
}
它不是一种不同类型的函数/闭包,它就像一个返回类型 - <$ c $
它帮助我的Java大脑想到
def bar =foo;
as
Object bar =foo;
Take the following controller:
package test
class TestController {
static defaultAction = "test"
def test() {
render "test"
}
}
Why is test
defined with def test() {
instead of something like void test() {
? Isn't the def
keyword only used for closures or functions in a script (i.e. not in a Groovy class)?
解决方案 Burt's answer is correct but the real problem I was having is that I misunderstood what def
is. Rather than being like var
in JavaScript, you can think of it like Object
in Java.
I thought that using def
was like doing (JavaScript)
var test = function() {
alert("test");
}
while in reality it's just like (Java)
public Object test() {
return someObject;
}
It's not a different kind of function/closure, it's like a return type—def
can be applied to any object (Groovy has no data primitives, so any value is also an object, unlike in Java).
It helps my Java brain to think of
def bar = "foo";
as
Object bar = "foo";
这篇关于为什么Grails要求我在控制器中使用`def`而不是`void`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!