问题
Consider the following code:
bdval = new BigDecimal(strval, new MathContext(attrib.getPrecision()));
bdval.setScale(attrib.getScale(), RoundingMode.HALF_UP);
PMD quite correctly says:
Useless operation on Immutable
So why do Immutable classes like BigDecimal
export mutators for properties?
回答1:
setScale()
doesn't mutate the BigDecimal it's called on. It returns a copy of the BigDecimal with the new scale value.
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);
来源:https://stackoverflow.com/questions/15462078/why-do-immutable-classes-provide-mutators