Groovy TIP 4: Objects are not null judgments and "?" Operator

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.