One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
In general you can use Object class for any type, but you have do type casting later!
eg:-
I have cooked up a plugin for IntelliJ that – in a way – gives you
var
in Java. It's a hack, so the usual disclaimers apply, but if you use IntelliJ for your Java development and want to try it out, it's at https://bitbucket.org/balpha/varsity.JEP - JDK Enhancement-Proposal
http://openjdk.java.net/jeps/286
JEP 286: Local-Variable Type Inference
Author Brian Goetz
As of Java 10, the equivalent is ...
var
.You can, in Java 10, but only for Local variables, meaning,
You can,
var anum = 10; var aString = "Var";
But can't,
var anull = null; // Since the type can't be inferred in this case
Check out the spec for more info.
With the release of JDK 10 on March 20, Java now includes a
var
reserved type name (not a keyword—see below) as specified in JEP 286. For local variables, the following is now valid in Java 10 or higher:The
var
reserved type name in Java is nearly identical to thevar
keyword in C# in that both allow for implicit typing (see below for important differences).var
in Java can only be used for implicit type inference in the following contexts (as enumerated in JEP 286: Goals):Therefore
var
cannot be used for fields, return types, class names, or interface names. Its rationale is to remove the need for including long type names when declaring and defining local variables, as stated in JEP 286 (authored by Brian Goetz):var
Scoping in JavaIt should be noted that
var
is not a keyword in Java, but rather a reserved type name. As quoted from JEP 286:Note that since
var
is a reserved type name and not a keyword, it can still be used for package names, method names, and variable names (along with its new type-interference role). For example, the following are all examples of valid uses ofvar
in Java:As quoted from JEP 286:
Differences Between
var
in Java & C#This is one notable difference between
var
in C# and Java include the following:var
can be used as a type name in C# but cannot be used as a class name or interface name in Java. According to the C# documentation (Implicitly Typed Local Variables):The ability to use
var
as a type name in C# creates some complexity and introduces some intricate resolution rules, which are avoided byvar
in Java by disallowingvar
as a class or interface name. For information on the complexities ofvar
type names in C#, see Restrictions apply to implicitly-typed variable declarations. For more information on the rationale behind the scoping decision for `var in Java, see JEP 286: Scoping Choices.