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
This feature is now available in Java SE 10. The static, type-safe var has finally made it into the java world :)
source: https://www.oracle.com/corporate/pressrelease/Java-10-032018.html
A simple solution (assuming you're using a decent IDE) is to just type 'int' everywhere and then get it to set the type for you.
I actually just added a class called 'var' so I don't have to type something different.
The code is still too verbose, but at least you don't have to type it!
You can take a look to Kotlin by JetBrains, but it's val. not var.
Lombok
supports var but it's still classified as experimental:Here is a pitfall to avoid when trying to use it in
IntelliJ IDEA
. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.Note that
val
is support byLombok
as well without modifying or creating alombok.config
.Java 10 did get local variable type inference, so now it has
var
which is pretty much equivalent to the C# one (so far as I am aware).It can also infer non-denotable types (types which couldn't be named in that place by the programmer; though which types are non-denotable is different, e.g. Java doesn't have an equivalent to C# anonymous types).
The one difference I could find is that in C#,
In Java 10
var
is not a legal type name.I know this is older but why not create a var class and create constructors with different types and depending on what constructors gets invoked you get var with different type. You could even build in methods to convert one type to another.