我喜欢 C# 中的“var”和 Groovy 中的“def”,而且我发现在 Java 中编写类型很痛苦。
假设我正在编写如下代码:
List<LongTypeName> results = new ArrayList<LongTypeName>();
或者
Map<TypeNameOne,TypeNameTwo> someLookup = fetchMeMyLookup();
在 Java + Eclipse 中完成此操作的最简单方法是什么?
我特别感兴趣的是当我开始生产线时我不能 100% 确定类型是什么的情况。
我当前的策略是始终将变量声明为“int”,然后返回到行的开头并执行“ctrl-1”,并接受 Eclipse 推断的类型。还有更好的选择吗?
我希望能够输入“def”或“var”,并让 Eclipse 在弄清楚后立即将其自动更正为正确的类型。
(也许我应该只用 Groovy 编程)
I like "var" from C# and "def" from Groovy, and I find writing out types in Java to be a pain.
Say I'm writing code like:
List<LongTypeName> results = new ArrayList<LongTypeName>();
or
Map<TypeNameOne,TypeNameTwo> someLookup = fetchMeMyLookup();
What's the easiest way to get this done in Java + Eclipse?
I'm especially interested in the case where I'm not 100% sure what the type will be when I start the line.
My current strategy is to always declare variables as "int", then go back to the start of the line and do "ctrl-1", and accept the type that Eclipse has inferred. Is there any better alternative?
What I would love is to be able to type "def" or "var" and have Eclipse auto-correct this to the correct type as soon as it can figure it out.
(Maybe I should just be programming in Groovy)
发布评论
评论(3)
new ArrayList();
Ctrl+2+L
创建一个新的局部变量两种类型类型都是“活动的” - 您可以循环浏览它们通过选择。在此示例中,名称建议是 list 和 arrayList,类型建议是
ArrayList
的所有可能接口和超类,:<代码>列表<字符串,<代码>集合<字符串>等new ArrayList<LongTypeName>();
Ctrl+2+L
to create a new local variableBoth type type are 'active' - you can tab through them an cycle through selections. In this example, the name proposals are list and arrayList and the type proposals are all possible interfaces and superclasses of
ArrayList<String>
, :List<String
,Collection<String>
etc.输入:
然后单击
someLookup
并按 Ctrl+1 快速修复“创建局部变量 someLookup”Type:
Then click on
someLookup
and hit Ctrl+1 for the quick fix of "Create local variable someLookup"Java 10 引入了局部变量的类型推断。
您现在可以使用特殊(保留)类型名称
var
,例如:请参阅 JEP 286了解详情。
Java 10 has introduced type inference for local variables.
You may now use the special (reserved) type name
var
, e.g.:See JEP 286 for details.