0

Not sure if this is an appropriate question for here, please let me know!

In Scala, the ever so useful Option class has an apply method in its companion object that allows us to quickly wrap any value into an Option:

def apply[A](x: A): Option[A] = if (x == null) None else Some(x)

This is super helpful when dealing with mixed Java/Scala code. As you can wrap null in an Option and get back a Scala friendly None. However, if you do Option(None) you receive a Some(None), when perhaps you would expect to receive a None back.

My question is why wasn't the design of that method something more like:

def apply[A](x: A): Option[A] = if (x == null || x == None) None else Some(x)

Does Some(None) make more sense in some scenarios? I would like the second approach to do something like:

val isNull = Option(someValue).isEmpty // returns false for Some(None)
  • Option() is applied to nullable values. Are you saying that you are passing in a nullable Option value? If so, rethink your coding practices. – BobDalgleish Jun 7 at 16:22
3

Well, the apply method was designed to create an option from a nullable value, and if you already have an Option, there's not really a need to create one. Also a Some(None) is valid in certain circumstances where you already have an Option and you want to call a method on its contents that also returns an Option, although you would generally use a flatMap or quickly call flatten afterward to avoid having that confusing situation for very long.

0

An option has 2 possible values at a high level, some or none.

Some(None) seems to be an option in an option

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.