AbuMariam
AbuMariam

Reputation: 3678

Groovy way to convert empty string to null

I want a Groovy function which will return null if the passed in value is an empty string and return the string otherwise. This was what I could come up with..

def emptyStringNullConverter(a) {
    return a?.toString()?.length() == 0 ? null : a
}

But is there a Groovier way to do this?

Upvotes: 2

Views: 1672

Answers (1)

tim_yates
tim_yates

Reputation: 171084

You could just do:

def emptyStringNullConverter(a) {
    a ?: null
}

Upvotes: 4

Related Questions