Ian - 3 months ago 12

Scala Question

I'm trying to combine to arrays that are wrapped in an

`Option`

`val a = Option(Array(1, 2, 3))`

val b = Option(Array(4,5))

val q = for {

x <- a

y <- b

} yield x ++ y

The problem is that if

`b`

`None`

`None`

`a`

`a`

`None`

`++`

`Nothing`

`b`

I tried the following in Cats but couldn't get it to work:

`Semigroup[Option[Array[Int]]].combine(a,b) // === a |+| b`

It tells me that:

`could not find implicit value for parameter ev: cats.kernel.Semigroup[Option[Array[Int]]]`

The resulting type should be the same as the types of

`a`

`b`

Answer

Preserving the type `Option[C[X]]`

, where `C`

is some collection type and `X`

is the element type of that collection, I came up with:

```
a.fold(b)(x => b.fold(a)(y => Option(x ++ y)))
```

Source (Stackoverflow)

Comments