info@sibulabs.com

Instagram

Instagram did not return a 200.

December 18, 2023 0

var is suitable for declaring local variables, including index variables in for-loops and resource variables in the try-with-resources statement.

However, it is important to note that var cannot be utilized for fields, method parameters, and method return types. The rationale behind this restriction lies in the fact that types in these contexts are explicitly specified in class files and Javadoc specifications. The use of type inference in these scenarios could lead to potential issues, as a modification to an initializer might alter the inferred type of the variable, causing unintended consequences.

In the case of local variables, this isn’t problematic since their scope is limited, and their types are not directly recorded in class files. However, for fields, method parameters, and method return types, the implications of type inference could result in source or binary incompatibility. For instance, if a method’s return type is inferred from its return statement, a change in the implementation might inadvertently alter the return type, causing compatibility issues.

While it may seem plausible to allow var for private fields and the return types of private methods, which are not part of APIs, the decision was made to restrict type inference even in these cases for the sake of simplicity. Extending the scope of type inference to include certain private fields and method returns would significantly increase the complexity of the feature without providing substantial benefits.