Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit wrap of Java Null

I need to access a large set of Java interfaces from Scala. These interfaces have methods that might return Null, and I want to convert them to Option[T]

I found other answers that describe Option.apply() like these

How to implicitly wrap a value that can be null or an array into an Scala Option

Option-izing Java getters

However, this requires that for each Java interface, I manually create a Scala wrapper. Like this...

class ScalaFoo extends JavaFoo {
  def bar = Option(super.bar)
}

That seems messy, hard to maintain, and prone to error. I don't want all that extra code that does nothing, and I want to automatically wrap all my Java interfaces, so that if one changes, the wrapper also changes.

Surely, there is a way to do this with implicits, isn't there?

like image 980
opus111 Avatar asked Mar 02 '14 17:03

opus111


People also ask

Can wrapper be null in Java?

Wrapper Class Objects Store Null Value The null value can't be stored in a variable of a primitive type, whereas it can be stored in an object of a wrapper class.

How do you handle not null in Java?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.


Video Answer


2 Answers

I recently ended up with something like this:

object Implicits {
  implicit class ConvertToOption[T](t: T) {
    def optional = Option(t)
  }
}

Usage:

Suppose you have a following Java interface:

public interface Fooable {
    public String getFoo();
}

public class Foo implements Fooable {
    public String getFoo() { 
        return null; 
    }
}

In your Scala code:

import Implicits._

val foo = new Foo()
val myOptionalValue = foo.getFoo.optional //returns an Option[String], in this case None because getFoo returns null
like image 67
serejja Avatar answered Oct 22 '22 19:10

serejja


I'm not aware of a great way to do this either. However I saw a nice approach on twitter recently:

import Option.{apply => ?}
val fooBar = ?(javaFoo.bar)
like image 30
joescii Avatar answered Oct 22 '22 20:10

joescii