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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With