Home > Mobile >  Why this method is ambiguous?
Why this method is ambiguous?

Time:10-17

I have two polymorphic methods that take two types of classes as input. I would like the stream based on the object to do two different actions. Instead he tells me that the method is ambiguous. Not using streams obviously work. My purpose is to use them. How can I solve?

Help me, I can't understand. Thanks.

Stream.of(1,"Text").forEach(Test::method);


    static void method(Integer i){
        System.out.println("i");
    }

    static void method(String i){
        System.out.println("s");
    }

CodePudding user response:

If you assigned the stream to a local variable you'll see that type of Stream.of(1,"Text") is Stream<Object>

Stream<Object> x = Stream.of(1,"Text");

Thus the type of the method that is needed for the forEach is:

static void method(Object obj){
    System.out.println("Object is: " obj);
}

If you had used Stream.of(1,2) or Stream.of("Hello", "Text") then the method calls would resolve as you expected.

CodePudding user response:

You can add a method who accept Object parameter, and go with this approach :

import java.util.stream.Stream;

public class Test {
static void method(Object o) {
    if(o instanceof String)
        method((String)o);
    if(o instanceof Integer)
        method((Integer)o);
}

static void method(Integer i) {
    System.out.println("i");
}

static void method(String i) {
    System.out.println("s");
}

public static void main(String[] args) {
    Stream.of(1, "Text").forEach(element -> {
        Test.method( element );
    });
}
}

CodePudding user response:

As the stream is raw (Stream<Object>) a method accepting an argument of Object type may be implemented to dispatch the call to appropriate overloaded method (null values should be handled to map to some specific method too):

Stream.of(1,"Text", null).forEach(MyClass::method);

static void method(Object o) {
    if (o instanceof Integer) {
        method((Integer) o);
    } else if (o instanceof String || null == o) {
        method((String) o);
    } else {
        method(o.toString());
    }
}

Output:

i
s
s
  • Related