Passing null to a generic Java method

Given the following wrapper for a JavaFX ObjectProperty:

import javafx.beans.property.ObjectProperty

class Wrapper[A](objectProperty: ObjectProperty[A]) {
  def value: Option[A] = Option(objectProperty.getValue)

  def value_=(newValue: Option[A]): Unit = objectProperty.setValue(newValue.orNull)
}

This does not compile because of a type mismatch in the setter method. (Required A; Found: Any).

This, of course, also happens if I was to try this:

def value_=(newValue: Option[A]): Unit = newValue match {
  case Some(value) => objectProperty.setValue(value)
  case None => objectProperty.setValue(null)
}

What is the correct way to pass null to a Java method?

It’s not really because of the Java method. Though there’s a higher chance that you run into this issue while interfacing with Java code since they’re more prone to use nulls and in Java null is a valid value for an unbounded type parameter.

The issue is that A has upper bound Any, so A could also be Int (or any other AnyVal) and then null is not a valid value. So if null has to be a valid value for every A, you need to have either A >: Null or A <: AnyRef. But since you are wrapping a Java API you may want to leave your A as it is and use a cast in your implementation: null.asInstanceOf[A].

2 Likes

I came up with that idea but it looked quite strange to me to cast null; even more I was not sure if this was actually possible.

Thank you for clarification!