本文介绍了为什么不可变类提供了mutators?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
bdval = new BigDecimal(strval, new MathContext(attrib.getPrecision()));
bdval.setScale(attrib.getScale(), RoundingMode.HALF_UP);
非常正确地说:
那么为什么像 BigDecimal
这样的Immutable类会为属性导出mutators?
So why do Immutable classes like BigDecimal
export mutators for properties?
推荐答案
setScale()
不会改变调用它的BigDecimal 。它返回BigDecimal的副本以及新的比例值。
setScale()
doesn't mutate the BigDecimal it's called on. It returns a copy of the BigDecimal with the new scale value.
PMD报告错误,因为您的代码错误:它忽略了操作的结果,使操作无效。你的代码应该是:
PMD reports an error because YOUR code is wrong: it ignores the result of the operation making the operation useless. Your code should be:
bdval = bdval.setScale(attrib.getScale(), RoundingMode.HALF_UP);
这篇关于为什么不可变类提供了mutators?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!