Class LocalVariableTypeInferenceExamples
java.lang.Object
net.jrodolfo.java_evolution.java10.LocalVariableTypeInferenceExamples
Demonstrates local variable type inference, introduced in Java 10 through the
var reserved type name.
Before Java 10, local variables sometimes repeated long generic types that were already obvious from the initializer. That made code noisier without adding much information.
var solves that local readability problem. It does not make Java
dynamically typed: the compiler still infers a specific static type from the
initializer. In Java 10 it is limited to local variables, including variables
in loops and try-with-resources blocks.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintcountNames(List<String> names) Usesvarfor a local variable whose constructor initializer makes a longer generic type obvious.Shows that avarvariable still has a real compile-time type.readFirstLine(String text) Usesvarin a try-with-resources declaration.Keeps the explicit type in the method signature because Java 10varis only for local variables.wordLengths(List<String> words) Usesvarwith a generic collection to avoid repeating the full type on both sides of the assignment.
-
Constructor Details
-
LocalVariableTypeInferenceExamples
public LocalVariableTypeInferenceExamples()
-
-
Method Details
-
countNames
-
wordLengths
-
readFirstLine
Usesvarin a try-with-resources declaration.- Parameters:
text- text read through aBufferedReader- Returns:
- the first line of the text
- Throws:
IOException- when reading fails
-
inferredTypeStillHasAConcreteClass
-
whereVarCanBeUsed
Keeps the explicit type in the method signature because Java 10varis only for local variables.- Returns:
- a sentence summarizing the scope of
var
-