vnskln
vnskln

Reputation: 3

Groovy - method starting with "is"

I found code in existing project and I don't know why it works. Class has a method with name starting with "is". I can call foo.isBar() and it simply does its job. But in mentioned code i saw using simple foo.bar, and it seems to also work. But i don't understand why. I have tested it in online groovy compiler and it still works, so it's not something specific to that project. Is it some feature of groovy language?

class Foo {
    boolean isBar() {
        return false
    }
}

Foo foo = new Foo()
//this one works
println foo.isBar()
//but why this one also works?
println foo.bar

Google search did not help. I don't even know exactly what I am looking for.

Upvotes: 0

Views: 381

Answers (1)

Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10405

Groove has Properties feature that introduces special naming convention (mostly following Java Beans specification).

Properties can be defined without backing field:

By convention, Groovy will recognize properties even if there is no backing field provided there are getters or setters that follow the Java Beans specification.

Example:

class PseudoProperties {
    // a pseudo property "name"
    void setName(String name) {}
    String getName() {}

    // a pseudo read-only property "age"
    int getAge() { 42 }

    // a pseudo write-only property "groovy"
    void setGroovy(boolean groovy) {  }
}
def p = new PseudoProperties()
p.name = 'Foo'                      
assert p.age == 42                  
p.groovy = true

It is generally recommended that the first two letters of a property name are lowercase and for multi-word properties that camel case is used. In those cases, generated getters and setters will have a name formed by capitalizing the property name and adding a get or set prefix (or optionally "is" for a boolean getter). So, getLength would be a getter for a length property and setFirstName a setter for a firstName property. isEmpty might be the getter method name for a property named empty.

You can read more about naming convention in the documentation

Upvotes: 1

Related Questions