IntelliJ IDEA在JAVA中使用+ =时会强调变量 [英] IntelliJ IDEA underlines variables when using += in JAVA

查看:889
本文介绍了IntelliJ IDEA在JAVA中使用+ =时会强调变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于新更新(2018.2)IntelliJ IDEA强调了变量,因此不必要地"重新分配了变量-但是,这包括每次使用"+ =".
这是IDE中的错误,还是我弄错了?
请以这个基本方法为例. (它只会添加一个数字列表.)

解决方案

这是一个新功能:

强调重新分配的局部变量和重新分配的参数

IntelliJ IDEA现在默认情况下突出显示了重新分配的局部变量和重新分配的参数.支持此功能的所有语言的属性(包括Java和Groovy)可以在 Preferences/Settings |编辑器配色方案|语言默认值|标识符|重新分配.

为什么可能有用?

如果变量/参数带有下划线,则说明您不能直接在lambda/anonymous类中使用它.

在读取很长的方法代码时,如果未对参数加下划线,则可以确定该方法中的任何地方都不会重新分配其值,并且该参数包含的值与传递给该方法的值完全相同. /p>

一些代码准则与重新分配的变量不符,您可能希望避免使用它们,以保持代码的清洁并使其更易于阅读/调试.

如今,许多开发人员更喜欢避免可变状态,仅在真正有必要的极少数情况下才重新分配变量.我们不想手动强制不变性,我们假设默认情况下所有内容都是不变的,并且希望引起人们对某些情况的关注.如果使用final标记非可变变量,则意味着在常规情况下需要编写更多代码,在特殊情况下则需要编写较少的代码. (现代语言中的BTW声明不可变的变量不需要编写其他代码,但是不幸的是,在Java中不需要.)

Java语言设计师Brian Goetz也喜欢IntelliJ IDEA突出显示重新分配的变量的方式(请参见他的推文).

Since the new update (2018.2) IntelliJ IDEA underlines variables, when they are "unnecessarily" reassigned - this includes, however, each use of "+=".
Is this a mistake in the IDE or am I getting it wrong?
Please see this basic method as an example. (It just adds a list of numbers.)

解决方案

It's a new feature of IntelliJ IDEA 2018.2:

Underlining reassigned local variables and reassigned parameters

IntelliJ IDEA now underlines reassigned local variables and reassigned parameters, by default. The attributes for all the languages supporting this feature, which for now include Java and Groovy, can be changed in Preferences/Settings | Editor | Color Scheme | Language Defaults | Identifiers | Reassigned.

Why it may be useful?

If the variable/parameter is underlined, you know that you can't use it in lambda/anonymous class directly.

When reading a very long method code, if the parameter is not underlined, you know for sure that its value is not reassigned anywhere in this method and it contains exactly the same value that was passed to this method at any point.

Some code guidelines are against reassigned variables and you may want to avoid them where possible to keep the code clean and make it easier to read/debug.

Nowadays many developers prefer to avoid mutable state, and reassign variables only in rare cases when it is really necessary. We don't want to manually enforce immutability, we suppose that everything is immutable by default and want to bring additional attention to the cases when something is not. If you use final to mark non-mutable variables it means that you need to write more code for regular cases and less code in exceptional cases. (BTW in modern languages declaring immutable variables doesn't require writing additional code, but unfortunately not in Java).

Brian Goetz, Java Language Architect, also likes the way IntelliJ IDEA highlights reassigned variables (see his tweet).

这篇关于IntelliJ IDEA在JAVA中使用+ =时会强调变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆