Scala’s Option class has an orNull method, whose signature is shown below.
orNull [A1 >: A](implicit ev : <:<[Null, A1]) : A1
I’m bewildered by the implicit thing. Would somebody please explain how it can be used, ideally with an example?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
To explain the implicit thing: orNull is a way of getting back from the Some|None idiom to Java’s value|null idiom (which is, of course, bad). Now only AnyRef values (instances of classes) can accept a null value.
So what we would have liked is
def orNull[A >: Null] = ..... But A is already set and we don’t want to restrict it in the definition of the trait. Therefore, orNull expects an evidence that A is a nullable type. This evidence is in the form of an implicit variable (hence the name ‘ev’)<:<[Null, A1]can be written asNull <:< A1seeing it like this, it is similar to ‘Null <: A1’. <:< is defined in Predef as well as the method that provides the implicit value namedconforms.I think the use of A1 is not strictly required here and is because orNull uses getOrElse (where the default given can be a super type of A)