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

.

+3


source to share


2 answers


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.

+2


source


You want to match yours Option[String]

with Option[User]

:



val userName: Option[String] = myList.find(...)
val user: Option[User] = userName.map(n => User(n))

      

+8


source







All Articles