Groovy snippets

Jul 20

I like the simplicity of languages like Ruby and JavaScript. In both of these languages, you can do something similar to:

foo = bar || "default"

This actually assigns either bar (if it is truthy), or "default" to foo.

Sadly, with Java and Groovy, foo will actually have either true or false as a value. Behold, there is a way to do the same thing with Groovy:

foo = bar ?: "default"

It’s kind of a play on the ternary operator.

This means I can reduce this code

User currentUser = User.findByName(user)

if (!currentUser) {
    currentUser = new User(name: user)
    currentUser.save()
}

session.user = currentUser

to the one liner:

session.user = User.findByName(user) ?: new User(name: user).save()