Method overload in groovy

I am trying to use the convenience of groovy script syntax to assign properties, but having problems with a specific case. I must be missing something here. I define class A, B, C as follows:

class A {

    A() {
        println "Constructed class A!"
    }

}

class B {

    B() {
        println "Constructed class B!"
    }

}

class C {

    private member 

    C() {
        println "Constructed class C!"
    }

    def setMember(A a) {

        println "Called setMember(A)!"
        member = a

    }

    def setMember(B b) {

        println "Called setMember(B)!"
        member = b

    }

}

And then try the following calls in the script:

c = new C()

c.setMember(new A()) // works
c.member = new A()   // works

c.setMember(new B()) // works
c.member = new B()   // doesn't work!

The last assignment leads to the error: "Unable to expose an object of class B to class A". Why doesn't he call the correct setMember method for class B, as for class A?

+3
source share
1 answer

The shortcut to use dot notation to call the set setter method does not check type. Instead, it seems to use the first entry in the list of methods with the given name and call it.

Pyrasun Groovy.

() , , Groovy . ,

c.@member = new B()

:

def setMember(def param) {
  if (param instanceof A) println "Called setMember(A)!"
  if (param instanceof B) println "Called setMember(B)!"

  member = param
}
+2

Source: https://habr.com/ru/post/1746686/


All Articles