Question: Is there a way to replace all var
declaration with actual types in IntelliJ IDEA? 问题:是否可以用IntelliJ IDEA中的实际类型替换所有var
声明?
Context: I implemented a large feature using vars but turns out all developers in the team are against using vars and I have to rework it back to actual types. 上下文:我使用vars实现了一个大型功能,但事实证明,团队中的所有开发人员都反对使用vars,因此我不得不将其重新设计为实际类型。
There is an inspection specifically for this: 有专门为此检查:
- Go to Analyze -> Run Inspection By Name (or Ctrl Alt Shift I by default) 转到“分析”->“按名称运行检查”(默认情况下, 按Ctrl Alt Shift I )
- Type enough of "Variable Type can by explicit" until you see it in the list, then select it 键入足够的“变量类型可以通过显式”,直到在列表中看到它,然后选择它
- Pick the scope you want to run the inspection over. 选择要运行检查的范围。
- In the ' Inspection Results ' dialog, click the lightbulb button labelled ' Replace 'var' with explicit type ' 在“ 检查结果 ”对话框中,点击标有“用明确类型替换” var”的灯泡按钮
You should carefully review the suggested fixes, as the inspection may well use the most specific type, eg ArrayList<Foo>
, whereas it may well be more appropriate to use List<Foo>
(there is no way for a tool to know that in all cases). 您应该仔细查看建议的修复程序,因为检查很可能使用了最特定的类型,例如ArrayList<Foo>
,而使用List<Foo>
可能更合适(工具无法知道所有情况)。
There is a complementary inspection called "Local variable type can be omitted", to replace explicit types with var
. 有一个名为“可以省略局部变量类型”的补充检查,以用var
替换显式类型。