Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do type inference apply in Java non generics

Tags:

This is how Java Tutorials define type inference:

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

Below, it explains type inference using all examples of generics.

My questions is : Do type inference in Java only applies when generics come into play ? If not, an example or two will be helpful where we can see it ?

like image 988
Number945 Avatar asked Mar 21 '17 08:03

Number945


1 Answers

In lambdas you do not have to specify argument types, and return types as well, they are automatically deduced. For example:

listOfStrings.stream().
        map((aString) -> {
              //do something
             anObject anobject = new anObject();
            return anobject;})

        .collect(Collectors.toList());

The type of the returned list is List<anObject>, and I did not have to specify that aString is of type String as it is infered by the listOfStrings type.

like image 135
zakaria amine Avatar answered Sep 23 '22 09:09

zakaria amine