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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With