am1212
am1212

Reputation: 553

How to extract values from Some() in Scala

I have Some() type Map[String, String], such as

Array[Option[Any]] = Array(Some(Map(String, String)

I want to return it as

Array(Map(String, String))

I've tried few different ways of extracting it- Let's say if

val x = Array(Some(Map(String, String)
val x1 = for (i <- 0 until x.length) yield { x.apply(i) }

but this returns IndexedSeq(Some(Map)), which is not what I want.

I tried pattern matching,

x.foreach { i =>
  i match {
    case Some(value) => value
    case _ => println("nothing") }}

another thing I tried that was somewhat successful was that

x.apply(0).get.asInstanceOf[Map[String, String]]

will do something what I want, but it only gets 0th index of the entire array and I'd want all the maps in the array. How can I extract Map type out of Some?

Upvotes: 3

Views: 2804

Answers (3)

TheManWhoKnows
TheManWhoKnows

Reputation: 31

Also when you talk just about single value you can try Some("test").head and for null simply Some(null).flatten

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

Generally, the pattern is either to use transformations on the Option[T], like map, flatMap, filter, etc.

The problem is, we'll need to add a type cast to retrieve the underlying Map[String, String] from Any. So we'll use flatten to remove any potentially None types and unwrap the Option, and asInstanceOf to retreive the type:

scala> val y = Array(Some(Map("1" -> "1")), Some(Map("2" -> "2")), None)
y: Array[Option[scala.collection.immutable.Map[String,String]]] = Array(Some(Map(1 -> 1)), Some(Map(2 -> 2)), None)

scala> y.flatten.map(_.asInstanceOf[Map[String, String]])
res7: Array[Map[String,String]] = Array(Map(1 -> 1), Map(2 -> 2))

Upvotes: 1

marstran
marstran

Reputation: 27971

If you want an Array[Any] from your Array[Option[Any]], you can use this for expression:

for {
    opt <- x
    value <- opt
} yield value

This will put the values of all the non-empty Options inside a new array.

It is equivalent to this:

x.flatMap(_.toArray[Any])

Here, all options will be converted to an array of either 0 or 1 element. All these arrays will then be flattened back to one single array containing all the values.

Upvotes: 2

Related Questions