Why can’t the java compiler solve this problem?

Why can't the compiler from collections. In the following example Emptyset() infers the correct type of result?

import java.util.*;
import java.io.*;

public class Test {
    public interface Option<A> {
        public <B> B option(B b,F<A,B> f);
    }

    public interface F<A,B> {
        public B f(A a);
    }

    public Collection<String> getColl() {
        Option<Integer> iopt = null;

        return iopt.option(Collections.emptySet(),new F<Integer,Collection<String>>() {
            public Collection<String> f(Integer i) {
                return Collections.singleton(i.toString());
            }
        });
    }
}

This is the compiler error message:

knuttycombe@knuttycombe-ubuntu:~/tmp/java$javac Test.java 
Test.java:16: <B>option(B,Test.F<java.lang.Integer,B>) in 
Test.Option<java.lang.Integer> cannot be applied to (java.util.Set<java.lang.Object>,<anonymous Test.F<java.lang.Integer,java.util.Collection<java.lang.String>>>)
            return iopt.option(Collections.emptySet(),Collection<String>>() {
                   ^
1 error

Now, of course, the following implementation of getcoll () works:

public Collection<String> getColl() {
        Option<Integer> iopt = null;

        Collection<String> empty = Collections.emptySet();
        return iopt.option(empty,Collection<String>>() {
            public Collection<String> f(Integer i) {
                return Collections.singleton(i.toString());
            }
        });
    }

And the whole intention of the type safe method for collections is to avoid the problem of using singleton collections (rather than static variables) Therefore, can the compiler not perform reasoning across multiple generic levels? What's going on?

Solution

Java requires a lot of manual operations through reasoning The type system can be better inferred in many cases, but in your case, the following will work:

print("Collections.<String>emptySet();");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>