Compare instances of Option[T] avoiding None == None

scala option
check if option is none scala
scala option(string)
scala option map or else
scala return none
scala get value from option
getorelse scala map
scala option toright

Yesterday I was suddenly enlighted and understood how and why people use 'map' method with Option to compare values. Yes, I'm a bit slow, sorry :)

I revised these very nice links and came to the question I would like to ask.

http://twitter.github.com/effectivescala

http://blog.tmorris.net/posts/scalaoption-cheat-sheet

In my Lift webapp I have some Option[User] and Option[Server] variables. I'm trying to find out if this User is admin of this Server by the following check

if(user.map(_.id) == server.map(_.adminId))

But I noticed that in case of 'user' is None and 'server' is also None this check succeeds which is not good for me (if any of them is None I'd like this check to fail). I could add user.isDefined condition but I feel there is more correct way to do it. Could you tell how to accomplish it in Scala way?

You could do it with pattern matching (which in this case is probably the clearest way):

(user, server) match {
  case (Some(user), Some(server)) if user.id == server.adminId =>
    // both ids are matching, handle this case here
  case _ =>
    // no match, handle this case here
}

You could also try as a one-liner but here I don't advise it as it's pretty obfuscated:

if ( user.flatMap{ user => server.map(_.adminId == user.id) }.getOrElse( false ) ) {
  // both ids are matching, handle this case here
}
else {
  // no match, handle this case here
}

Finally, if you only have to handle the case where the ids match (and would just do nothing if there is not), using a for comprehension is not too bad of an option (no pun intended):

for ( user <- user; server <- server if user.id == server.adminId ) {
  // both ids are matching, handle this case here
}

Scala best practice: How to use the Option/Some/None pattern , to int � compare strings with == � a 'chomp' method � find regex in string See that recipe for examples of how to use an Option in those situations. scala> val x = toInt("foo") x: Option[Int] = None def divideXByY(x: Int, y: Int): Either[String, Int] = { if (y == 0) Left("Dude, can't divide by 0") else Right(x / y) }. In programing language, Comparing two values for equality is ubiquitous. We define an equals method for a Scala class so we can compare object instances to each other. In Scala, equality method signifying object identity, however, it’s not used much. In scala, Three different equality methods available – The equals Method; The == and != Methods

I got used to the combination of exists / contains for this purpose.

When comparing two options of the same type:

o1.exists(o2.contains)

In your case this can be applied using map:

user.map(_.id).exists(server.map(_.adminId).contains)

Option equality, Is there a succinct way to compare equality between two Options, but which returns false in the case of None? Sign in to reply even sure what it does. I think I like yours better, assuming that opt1 == opt2 is the same as Weirdly enough, I can't figure out where the equals/== method is defined for Option. Discussion. In Scala you test object equality with the == method. This is different than Java, where you use the equals method to compare two objects.. In Scala, the == method defined in the AnyRef class first checks for null values, and then calls the equals method on the first object (i.e., this) to see if the two objects are equal.

you can use a for comprehension

def isAdmin(server: Option[Server])(user: Option[User]): Boolean = (for {
    s <- server
    u <- user
  } yield (u.id == s.adminId)
).getOrElse(false)

The comprehension results in a Option[Boolean] from which you get the value or false if there's no value (the case where any of the options is None, as you requested)

Why curried?

I made the method curried, so you can define you function for a specific server, and then reuse that to check many users

def isMyServerAdmin = isAdmin(Some(myServer)) _

isMyServerAdmin(Some(user1)) = true
isMyServerAdmin(Some(user2)) = false
isMyServerAdmin(None) = false

Programming Scala: Scalability = Functional Programming + Objects, Scalability = Functional Programming + Objects Dean Wampler, Alex Payne _n retrieves the nth item from tuple t, starting at one, not zero, fol‐lowing historical Option,. Some,. and. None: Avoiding. nulls. Let's discuss three useful types that� When you compare strings, you define an order among them. Comparisons are used to sort a sequence of strings. Once the sequence is in a known order, it is easier to search, both for software and for humans.

We can make use of Option#zip to work with an Option of the tuple user/server:

user zip server exists { case (user, server) => user.id == server.adminId }

where the behavior of Option#zip is:

Some(User(id = "hello")) zip Some(Server(adminId = "world"))
// Some((User("hello"), Server("world")))
Some(User(id = "hello")) zip None        // None
None zip Some(Server(adminId = "world")) // None
None zip None                            // None

and where Option#exists applies a predicate on the optional tuple produced by zip.

Idiomatic Scala: Your Options Do Not Match, if (expr == true) { return true; } else { return false; } Option instance is to treat it as a collection or monad and use map , flatMap , filter , or val opt = Option(1) val a = opt match { case Some(x) => x + 1 case None It is not uncommon for methods or data structures of type Option[T] to be revamped to something like Seq[T] . An instance of the Scala None class; Because Some and None are both children of Option, your function signature just declares that you're returning an Option that contains some type (such as the Int type shown below). At the very least, this has the tremendous benefit of letting the user of your function know what’s going on.

The Science of Functional Programming (draft version), has In that implementation, the empty option None[T]() a type parameter. might be missing and helps the programmer to remember to handle both cases. To avoid repeating the code, we can implement this design pattern as a function that � Non vs None . No, none, non, no one etc. are some of the words in English language that are very confusing for students of English. This is because of the fact that all these words have similar meanings. However, despite similarities, there are two words non and none that remain a source of worry for the learners.

Scala Tutorial: Using Options, Some, and None, By representing values as either an instance of Some or None, Scala provides a In Scala, the Option[T] class serves as a container for zero or one element For example, the Scala Collections API uses optionals to avoid this issue: Best Comparison: Angular 2 vs Angular 1 Top ES6 Concepts for 2018� Scala Option[ T ] is a container for zero or one element of a given type. An Option[T] can be either Some[T] or None object, which represents a missing value. For instance, the get method of Scala's Map produces Some(value) if a value corresponding to a given key has been found, or None if the given key is not defined in the Map.

Veterinary Medical Education: A Practical Guide, Examples: 6) How many mg of Enrofloxacin are needed for a 20 kg dog if the dose 6 Avoid Using None of the Above Questions that employ none of the above as In the case of Question 8, option a is a recommended approach, but there are Which statistical test would you use to compare the raters' scores in order to� For instance, they’re baked into the Play Framework’s Anorm database library, where you use Option/Some/None for database table fields that can be null. In the following example, the third field may be null in the database, so it’s handled using Some and None , as shown:

Comments
  • the one-liner can be simplified a bit: user.exists(u => server.exists(_.adminId==u.id))
  • Correct, well spotted. I still don't think a one-liner is a good idea here, even if your version is much more concise (as the intent is still somewhat obfuscated).