Niro
Niro

Reputation: 443

Unpacking a Tuple of Option in scala

I have two Option[BigDecimal] vals that I would like to perform an operation on. I am trying to do this via map.

(a,b) map {case(a1: BigDecimal, b1: BigDecimal) => a + b
       case _ => 0}

but apparently I can't use a map on Tuple of optionals. Does anyone have any idea how to achieve that using map?

Upvotes: 0

Views: 1292

Answers (6)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

Using Seq and map as required in question,

Seq(a,b).map(_.getOrElse(BigDecimal(0))).sum

( where a and b are of Option[BigDecimal] type )

Upvotes: 0

talex
talex

Reputation: 20566

But you can use match

  (v1, v2) match {
    case (Some(a), Some(b)) => a + b
    case _ => 0
  }

If both v1 and v2 is present then returns sum, returns 0 otherwise.

UPDATE: In case you want sum of all present element you can do this:

val result = Seq(value._1, value._2)
  .flatten
  .fold[Integer](0)((a, b) => a + b)

Upvotes: 0

pme
pme

Reputation: 14813

Here is a solution with a Seq:

Seq(a,b).flatten.sum

Upvotes: 4

Raman Mishra
Raman Mishra

Reputation: 2686

I think this is what you want to do.

val a = Some(1)
val b = Some(2)

  val ans = (a, b) match {
    case (Some(a1), Some(b1)) => a1 + b1

    case _ => 0
  }
println(ans) // 3

you can also do like this:

a.getOrElse(0) + b.getOrElse(0)

Upvotes: -1

Tim
Tim

Reputation: 27431

If you want to default to 0 use this:

a.getOrElse(0) + b.getOrElse(0)

If you want to check that both values are valid, do this:

a.map(av => b.map(av + _))

or this

for {
  av <- a
  bv <- b
} yield av + bv

Both will give None if either a or b is None, otherwise it will give Some(a+b). Use getOrElse(0) on the result if you want the result to default to 0 in this case.

Upvotes: 1

Argurth
Argurth

Reputation: 644

You can simply do :

(a, b) match {
  case (Some(sa), Some(sb)) => sa + sb
  case _ => 0
}

You could also do :

(a, b) match {
  case (Some(sa), Some(sb)) => sa + sb
  case (Some(sa), None) => sa
  case (None, Some(sb)) => sb
  case _ => 0
}

If you want to consider the cases where only one of them is equal to None

Upvotes: 0

Related Questions