我正在尝试创建一个case class,它使用特定的MathContext (RoundUp,精确2)将BigDecimal作为值保存。文件上说BigDecimal.mc是一个val,所以没有简单的重新分配。所以我想出了两个解决方案。第一,这个
case class Test(number: BigDecimal)
object Test {
def apply(n) = new Test(n, new java.math.MathContext(2))
} 我不喜欢这个词,因为它可以用new关键字来环绕。
case class Test(var number: BigDecimal){
number = BigDecimal(number.toString, new java.math.MathContext(2))
}第二种方法可以工作,但是很难看,而且会产生额外的开销。我只是想知道我是否忽略了一些简单而优雅的东西。
发布于 2018-01-12 21:05:01
如何使构造函数是私有的,从而迫使每个人都使用apply
// constructor is private - use apply instead!
case class MyBigDecimal private(number: BigDecimal)
object MyBigDecimal {
private val defaultContext = new java.math.MathContext(2)
def apply(number: BigDecimal) = new MyBigDecimal(BigDecimal(number.bigDecimal, defaultContext))
}另外,您的第二个示例可以重写为只是丑陋,但没有那么低效:
case class MyBigDecimalWithVar(var number: BigDecimal) {
number = BigDecimal(number.bigDecimal, new java.math.MathContext(2))
}发布于 2018-01-12 11:42:23
import scala.languageFeature.implicitConversions
import java.math.{MathContext, BigDecimal}
trait BigDecimalSpecial {
def specialValue: BigDecimal
def mathContext: MathContext
}
object BigDecimalSpecial {
case class BigDecimalSpecial1(bd: BigDecimal) extends BigDecimalSpecial {
val mathContext = new MathContext(2)
val specialValue = new BigDecimal(bd.toString(), mathContext)
}
implicit def toBigDecimalSpecial1(bd: BigDecimal): BigDecimalSpecial = BigDecimalSpecial1(bd)
}
import BigDecimalSpecial._
val b = new BigDecimal("2.353453")
// b: java.math.BigDecimal = 2.353453
val forced = b.specialValue
// forced: java.math.BigDecimal = 2.4https://stackoverflow.com/questions/48223982
复制相似问题