Groovy and Grails Groovy Language Fundamentals & Metaprogramming 1 — Questions and Answers
Question 1: In Groovy, what does the `?.` operator do?
- Performs a strict equality check
- Safely navigates null references, returning null instead of throwing NullPointerException (Correct answer)
- Declares an optional method parameter
- Casts an object to a nullable type
Correct answer: Safely navigates null references, returning null instead of throwing NullPointerException
The `?.` (safe navigation) operator returns null if the object on its left is null, preventing NullPointerException.
Question 2: Which of the following correctly defines a Groovy closure that accepts two parameters and returns their sum?
- def sum = { a, b -> a + b } (Correct answer)
- def sum = (a, b) -> a + b
- def sum = closure(a, b) { a + b }
- def sum = [a, b] { return a + b }
Correct answer: def sum = { a, b -> a + b }
Groovy closures are defined with curly braces, parameters listed before `->`, and the body after.
Question 3: What is the implicit variable name for the single parameter of a Groovy closure when no parameter is declared?
- self
- arg
- it (Correct answer)
- param
Correct answer: it
When a Groovy closure has one parameter and no explicit declaration, Groovy automatically creates a variable named `it`.
Question 4: In Groovy, what is the result of `[1, 2, 3].collect { it * 2 }`?
- [2, 4, 6] (Correct answer)
- 6
- [1, 4, 9]
- null
Correct answer: [2, 4, 6]
`collect` transforms each element by applying the closure, so multiplying each by 2 yields [2, 4, 6].
Question 5: Which Groovy GDK method filters a list and returns only elements that match a condition?
- collect
- inject
- findAll (Correct answer)
- each
Correct answer: findAll
`findAll` iterates over a collection and returns a new list of elements for which the closure returns true.
Question 6: What does the Groovy `def` keyword indicate when used for a variable declaration?
- The variable is final and cannot be reassigned
- The variable is statically typed as Object
- The variable is dynamically typed and can hold any value (Correct answer)
- The variable is private to the current class
Correct answer: The variable is dynamically typed and can hold any value
`def` in Groovy declares a dynamically typed variable backed by the `Object` type at compile time, allowing any value to be assigned.
Question 7: What is the output of the following Groovy code: `println 'Hello' * 3`?
- HelloHelloHello (Correct answer)
- Hello3
- 3Hello
- Compilation error
Correct answer: HelloHelloHello
Groovy's String `multiply` operator replicates the string the specified number of times, producing 'HelloHelloHello'.
In Groovy, what does the `?.` operator do?