local variable type inference with instance and static initializers

Local type variable inference is the formal name of “var” in Java. From the name, you might deduce some things about allowed or disallowed locations. For example, a local variable in a method is allowed and an instance variable declaration is not.

Scopes that are even more granular are also allowed such as inside a for loop or try with resources statement.

I learned today that instance and static initializers are allowed as well.

public class LVTI {
public int myValue;
{
var temp = 3;
myValue = temp;
}
}
}

In hindsight, this makes sense. An initializer is a block of code. Which can have local variables.

For more on local variable type inference, please see the official style guidelines.

Leave a Reply

Your email address will not be published. Required fields are marked *