warch
warch

Reputation: 2599

How to handle groovy ambiguous method overload gracefully

I know there are similar questions but the answers are not satisfying.

I get an Groovy ambiguous method overload error when calling a method with null as parameter.

e.g.:

class A{
    sampleMethod (B bObj){
        if(bObj == null) {
            handleNullArgumentGracefully()
        }
        ... do some cool stuff ...
    }

    sampleMethod (C cObj){
        ... do some other cool stuff ...
    }
}

now when i call sampleMethod(null) groovy does not know which method it should invoke. Thats clear but is there a possibility to set one method of these two as default method to handle such null calls? I want to handle this on the callee side and not on the caller side (i do not want to cast something on the caller side)

UPDATE: i found a solution how it could work but i don´t know why: convert the non default method to a closure property

class app {
    static void main(String[] args) {
        def a = new A()
        a.sampleMethod(new B())
        a.sampleMethod(new C())
        a.sampleMethod(null)
    }
}

class A {
    def sampleMethod(B bObj = null) {
        if (bObj == null) {
            println("handle null")
        }
        println("1")
    }

    def sampleMethod = { C cObj ->
        println("2")
    }
}

class B {

}

class C {

}

Upvotes: 2

Views: 5417

Answers (1)

daggett
daggett

Reputation: 28564

the following will fail with Ambiguous method overloading for method A#sampleMethod

class A{
    def sampleMethod (Number o=null){
        println "num $o"
    }

    def sampleMethod (String o){
        println "str $o"
    }
}

new A().sampleMethod(null)

this one will work (Object will be called for null):

class A{
    def sampleMethod (Number o=null){
        println "num $o"
    }

    def sampleMethod (String o){
        println "str $o"
    }

    def sampleMethod(Object o){
        println "obj $o"
    }
}

new A().sampleMethod(null)

but i like this one:

class A{
    def _sampleMethod (Number o){
        println "num $o"
    }

    def _sampleMethod (String o){
        println "str $o"
    }

    def sampleMethod(Object o){
        if(o==null){
            println "null"
            return null
        }else if(o instanceof Number){
            return _sampleMethod ((Number) o)
        }else if(o instanceof String){
            return _sampleMethod ((String) o)
        }
        throw new IllegalArgumentException("wrong argument type: ${o.getClass()}")
    }
}

new A().sampleMethod(null)

Upvotes: 2

Related Questions