For a domain class object, as in the following example:
class Empl
{
String name
}
We need to manipulate it, such as printing the value of the "name" attribute, and we first have to make a non-empty judgment on it, as follows:
def em
if(em)
{
println"name: $em.name"
}
em = new Empl()
em.name = 'Tom'
if(em)
{
println"name: $em.name"
}
Obviously, if you do not do non-null judgment, then the first println statement throws a exception, makes the judgment, then does not have any question.
Of course, for our agile programming, the IF statement above, though simple, is still troublesome. For this reason, the groovy language provides us with a "?." Operator.
Use the "?." operator, we can change the above statement paragraph to read as follows:
def em
println"name: ${em?.name}"
em = new Empl()
em.name = 'Tom'
println"name: ${em?.name}"
Which, "em?." is to determine whether the EM object is empty and, if it is empty, to not calculate further, but to return the entire formula to a null.
The execution result of the preceding statement paragraph is:
Name:null
Name:tom
This simplification really makes our coding a lot easier.
We can even write code like the following:
println "city name: ${em?". Addr? City?. Name} "
Think about how tedious it would be if such a code were judged with an if statement.
When it comes to "?" operator, we can easily recall the Java language "?" operator, think of a line of code similar to the following:
def em
println em==null?"":em.name
This used to be a simplification for us by the Java language we talked about. For such a simplified statement, the Groovy language still makes a further simplification for us:
def em
println em ? em.name:""
Is it a little simpler?
It's worth noting, "em?" Is true when Em object is not empty, so in the above statement, "Em.name" is in front, and "" is in the back.