Tomasz Dziurko
Tomasz Dziurko

Reputation: 1688

How could I simplify this Scala Option usage

I have following code that get parameter and if it is valid ObjectId, converts it to Option[ObjectId] and otherwise, returns None.

I was thinking how it could be simplified, but didn't find anything particularly better.

Note: params.get("desiredImage") is Option[String]

val imageId: Option[ObjectId] = params.get("imageId") match {
  case None => None
  case Some(x) => {
    if (ObjectId.isValid(x)) {
      Some(new ObjectId(x))
    } else {
      None
    }
  }
}

Upvotes: 2

Views: 160

Answers (4)

Andrey
Andrey

Reputation: 750

For your own piece of code you have a nice option to cut it a little by using case ... if:

val imageId: Option[ObjectId] = params.get("imageId") match {
  case Some(x) if ObjectId.isValid(x) => Some(new ObjectId(x))
  case _ => None
}

Upvotes: 0

Antoine Comte
Antoine Comte

Reputation: 166

you can also use a for comprehension:

val imageId  = for ( x <- params.get("imageId") if ObjectId.isValid(x)) 
                   yield new ObjectId(x)

Upvotes: 3

Jens Halm
Jens Halm

Reputation: 499

You can also use collect to do it in a single operation:

val imageId: Option[ObjectId] = params.get("imageId") collect { 
  case x if ObjectId.isValid(x) => new ObjectId(x) 
}

Upvotes: 7

Lee
Lee

Reputation: 144106

You can use filter:

val imageId: Option[ObjectId] = params.get("imageId")
       .filter (ObjectId.isValid)
       .map(new ObjectId(_))

Upvotes: 5

Related Questions