Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if there's None in List[Option[_]] and return the element's name?

Tags:

scala

I have multiple Option's. I want to check if they hold a value. If an Option is None, I want to reply to user about this. Else proceed.

This is what I have done:

val name:Option[String]
val email:Option[String]
val pass:Option[String]
val i = List(name,email,pass).find(x => x match{
  case None => true
  case _ => false
})
i match{
  case Some(x) => Ok("Bad Request")
  case None => {
    //move forward
  }
}

Above I can replace find with contains, but this is a very dirty way. How can I make it elegant and monadic?

Edit: I would also like to know what element was None.

like image 258
Jatin Avatar asked Aug 17 '13 08:08

Jatin


People also ask

How do you check if all elements of a list are none?

To check if all values in a list are None: Use the list. count() method to count the None values in the list. If the number of None values is equal to the list's length, all values in the list are None .

How do you check if all values in list are empty Python?

Solution 3: Using len() In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.

How do I check if a string is not in a list Python?

Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.


2 Answers

Another way is as a for-comprehension:

val outcome = for {
  nm <- name
  em <- email
  pwd <- pass
  result = doSomething(nm, em, pwd) // where def doSomething(name: String, email: String, password: String): ResultType = ???
} yield (result)

This will generate outcome as a Some(result), which you can interrogate in various ways (all the methods available to the collections classes: map, filter, foreach, etc.). Eg:

outcome.map(Ok(result)).orElse(Ok("Bad Request"))
like image 105
Shadowlands Avatar answered Jan 01 '23 21:01

Shadowlands


  val ok = Seq(name, email, pass).forall(_.isDefined)
like image 28
Björn Jacobs Avatar answered Jan 01 '23 19:01

Björn Jacobs