Skip to content

Potential bug converting an Option of Java BigDecimal to an Option of Scala BigDecimal #6567

@scabug

Description

@scabug

I have been experience problems converting between an Option of a Java BigDecimal to an Option of a Scala BigDecimal.

For example, the following assertion fails:

import java.math.{BigDecimal => JBigDecimal}

object BigDecimalBug extends App {
  val nullJavaBigDecimal: JBigDecimal = null
  val x: Option[BigDecimal] = Option(nullJavaBigDecimal)
  assert(x == None)
}

The variable x is not actually None but a Some of the Scala BigDecimal object. The Scala BigDecimal object is incorrectly formed with the internal data structure set to null.

I have resolved this using the following implicit conversion, but wanted to highlight this in case this is perceived as an issue with the BigDecimal conversion logic.

object BigDecimalBug extends App {
  implicit def convertJBigDecimalOption(javaBigDecimal: JBigDecimal): Option[BigDecimal] = 
    Option(javaBigDecimal) map { x => BigDecimal(x.toString) }

  val nullJavaBigDecimal: JBigDecimal = null
  val y: Option[BigDecimal] = nullJavaBigDecimal
  assert(y == None)
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions