lapots
lapots

Reputation: 13395

Does groovy implicitly call find on Matcher when cast to boolean?

When I do like this

println "line with 1 digit" =~ /\d+/

It returns

java.util.regex.Matcher[pattern=\d+ region=0,17 lastmatch=]

But when I cast it to boolean - it return true or false depending on whether it was able to find the pattern in the string

println ((boolean) "line with 1 digit" =~ /\d+/) // true
println ((boolean) "line with no digits" =~ /\d+/) // false

Does that mean that during cast to boolean it invokes find method implicitly?

Upvotes: 3

Views: 473

Answers (1)

Jérémie B
Jérémie B

Reputation: 11022

It's called "groovy truth" : a set of rules to coerce an instance to a boolean.

Under the hood, Groovy calls the method asBoolean() on this object. This method can be implemented on a class, or injected through a category. Look at the various "asBoolean" methods in DefaultGroovyMethods or the implementation of asBoolean(Matcher) :

public static boolean asBoolean(Matcher matcher) {
    RegexSupport.setLastMatcher(matcher);
    return matcher.find();
}

Upvotes: 2

Related Questions