Why does Grails require that I use `def` instead of `void` in a controller?
Asked Answered
D

2

8

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)?

Durnan answered 12/2, 2012 at 6:0 Comment(0)
D
6

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";
Durnan answered 12/2, 2012 at 6:0 Comment(0)
B
16

render is void so in this case the test action could be void, but in the case where you return a model map the action has to be non-void:

def create() {
   [personInstance: new Person(params)]
}

Since some actions can return a value and some don't, the general syntax has to return def to support all variants.

Battleship answered 12/2, 2012 at 6:59 Comment(0)
D
6

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";
Durnan answered 12/2, 2012 at 6:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.