Question

I'm trying to do something that seems like it should have a straight forward syntax/function in scala. I just don't know what that is. I'm trying to convert the contained value of an Option (if it is not None) to another type.

Simply I want to know what the code would be if I wanted to implement the following function

def myFunc(inVal:Option[Double]):Option[BigDecimal] = {
    //Code I need goes here
}

Note: I am not actually implementing this function, it just is the clearest way for me to demonstrate what I need

Was it helpful?

Solution

def myFunc(inVal: Option[Double]): Option[BigDecimal] =
  inVal map {d => d: BigDecimal}

In general if you want to transform value in container (Option, Seq, List, Try, Future, etc) you should use method map on this container.

Method map accepts lambda (function) as parameter and applies this function to all elements. map should not change the count of elements: map on Some will never return None.

You could use method BigDecimal.apply to convert Double to BigDecimal like this:

BigDecimal(1.1)
// res0: scala.math.BigDecimal = 1.1

But there is also an implicit conversion from Double to BigDecimal, so you could just specify desired type like this:

1.1: BigDecimal
// res0: scala.math.BigDecimal = 1.1

val bd: BigDecimal = 1.2

PS: type inference allows you to use d => d instead of d => d: BigDecimal here, but it will make your code very unclear.

OTHER TIPS

def myFunc(inVal: Option[Double]): Option[BigDecimal] = inVal map { BigDecimal(_) }

or

def myFunc(inVal: Option[Double]): Option[BigDecimal] = inVal map { BigDecimal.apply }

It works because Option is a Functor (no monadic trick in this simple use case)

Extending @senia's and @Yann Moisan's answers, if you want to keep something wrapped inside Option[] while still supplying a default value during conversion phase (could be a requirement down-the-line in your framework), you can use this:

def myFunc(inVal: Option[Double]): Option[BigDecimal] = {
  Some(inVal.map(BigDecimal(_)).getOrElse(BigDecimal(0.0)))
}

It would not only convert your Option[Double] into Option[BigDecimal] but also create a default BigDecimal (with value 0.0) in case the origin Option[Double] turns out to be null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top