Geek
Geek

Reputation: 27203

How does a compiler infer type for a parameterless method?

From Effective Java :

One noteworthy feature of generic methods is that you needn’t specify the value of the type parameter explicitly as you must when invoking generic con- structors. The compiler figures out the value of the type parameters by examining the types of the method arguments.

So how does the compiler infer type in case of a method that takes no parameter ?

For example consider the following static factory method that creates a new HashMap every time it is called :

// Generic static factory method
public static <K,V> HashMap<K,V> newHashMap() {
return new HashMap<K,V>();
}

And when the method is called like :

Map<String,String> pair = newHashMap(); //it returns a Map<String,String>

and when it called like

Map<String, List<String>> anagrams =newHashMap(); // it returns a Map<String,List<String>

Upvotes: 1

Views: 142

Answers (2)

Kelly S. French
Kelly S. French

Reputation: 12344

The compiler has only a limited number of variables on which to infer types. If a method takes no arguments, then the method can only be a simple override, since return values cannot be used to type methods, that leaves the name of the method itself. The compiler has to choose how far up the inheritance chain to select which parent/child class has the method to actually be called.

Upvotes: 0

Perception
Perception

Reputation: 80623

It infers it based on the variable type that the return is assigned too.

public class GenericTest {

    public static void main(final String[] args) {
        final GenericTest test = new GenericTest();
        String data = test.echo();
    }

    public <T> T echo() {
        return null;
    }
}

In code example above, the compiler infers the generic parameter type based on the type of the data field, in this case String.

Upvotes: 4

Related Questions