2

It seems the groovy also support the compiling mode, using groovyc , If I run the following code with dynamic script calling way, I will get "String" method called.

Why I still got "String" even if I compiled the code using groovyc? The type of variable a is "Object", so I expected after compiling the code, I will get the "Object" function called.

Object a = "123"

def foo(Object a) {
    println "Object"
}

def foo(String a) {
    println "String"
}

foo(a)
Jayan
  • 18,003
  • 15
  • 89
  • 143
python
  • 1,870
  • 4
  • 24
  • 35
  • Object a = "123" is like Object a=(GString) "123"... it will get dispatched to most matching method call.. – Jayan Dec 05 '15 at 14:16
  • related reading: http://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type (foo is a method on a Class that represents your script ) – Jayan Dec 05 '15 at 14:18
  • 1
    Why would you expect the semantics to change after compilation? – Oliver Charlesworth Dec 05 '15 at 15:29
  • 1
    @jayan: that link is about the *opposite* behaviour to what the OP is observing... – Oliver Charlesworth Dec 05 '15 at 15:31
  • @Oliver Charlesworth : I posted the link hastily. Groovy has section about the diff with Java. This is one, and exact opposite behavior. – Jayan Dec 05 '15 at 15:42

1 Answers1

2

Here is relevant section from groovy-docs

In Groovy, the methods which will be invoked are chosen at runtime. This is called runtime dispatch or multi-methods. It means that the method will be chosen based on the types of the arguments at runtime. In Java, this is the opposite: methods are chosen at compile time, based on the declared types.

There is a sample code in '2. Multi-methods' section, not copying here.

Finally mandatory link to MrHaki's groovy goodness page on this topic

Community
  • 1
  • 1
Jayan
  • 18,003
  • 15
  • 89
  • 143