When to use Option # orNull
As I understand it, we should avoid using it null
in Scala. And if any field does not logically have a "no-value" value, we shouldn't use Option
to avoid using Option
s.
So let's take a look at the code. I have class
case class User (name: String)
and I am 100% sure that the field name
cannot be null
, and because of this I only used String
instead Option[String]
.
The problem is that some standard Scala methods come back to me Option
s. (In my case, the method IterableLike#find
returns a parameter)
So the question is, how can I create an instance User
when I have name
it wrapped in Option
? To be a little clear, this is the code:
val userName: Option[String] = myList.find(...)
val user = User(userName.get) // or may be I should use userName.orNull ? or throw exception?
I heard that Option.get
not an elegant solution. orNull
the method is almost the same as get
.
source to share
orNull
provided mainly for Java interop. Use null
as a reference in many Java libraries is ubiquitous, but orNull
serves as a small piece of syntactic sugar. It's basically simple myOption.getOrElse(null)
, but with a function name that allows for a bit of cleanup.
Usage orNull
in a pure Scala project would be odd to say the least.
source to share