What is the equivalent of the C# 'var' key

2019-01-10 06:12发布

One use of the var keyword in C# is implicit type declaration. What is the Java equivalent syntax for var?

标签: java keyword var
15条回答
Explosion°爆炸
2楼-- · 2019-01-10 06:32

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-10 06:34

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!

查看更多
4楼-- · 2019-01-10 06:35

You can take a look to Kotlin by JetBrains, but it's val. not var.

查看更多
姐就是有狂的资本
5楼-- · 2019-01-10 06:35

Lombok supports var but it's still classified as experimental:

import lombok.experimental.var;

var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);

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 by Lombok as well without modifying or creating a lombok.config.

查看更多
甜甜的少女心
6楼-- · 2019-01-10 06:36

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#,

If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

In Java 10 var is not a legal type name.

查看更多
小情绪 Triste *
7楼-- · 2019-01-10 06:38

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.

查看更多
登录 后发表回答