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
If you add Lombok to your project you can use its val keyword.
http://projectlombok.org/features/val.html
There is none. Alas, you have to type out the full type name.
Edit: 7 years after being posted, type inference for local variables (with
var
) was added in Java 10.Edit: 6 years after being posted, to collect some of the comments from below:
The reason C# has the
var
keyword is because it's possible to have Types that have no name in .NET. Eg:In this case, it would be impossible to give a proper type to
myData
. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.var
is not the same asdynamic
.var
iables are still 100% statically typed. This will not compile:var
is also useful when the type is obvious from context. For example:I can say that in any code that I am responsible for,
currentUser
has aUser
or derived class in it. Obviously, if your implementation ofUser.GetCurrent
return an int, then maybe this is a detriment to you.This has nothing to do with
var
, but if you have weird inheritance hierarchies where you shadow methods with other methods (egnew public void DoAThing()
), don't forget that non-virtual methods are affected by the Type they are cast as.I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:
As indicated, virtual methods are not affected by this.
No, there is no non-clumsy way to initialize a
var
without an actual variable.In this case, just do it the old fashioned way:
It will be supported in JDK 10. It's even possible to see it in action in the early access build.
The JEP 286:
So now instead of writing:
You write:
Notes:
var
is now a reserved type nameIf you want to give it a try without installing Java on your local system, I created a Docker image with JDK 10 installed on it: