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?
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With