Convert Scala Unit to Java Void

Viewed 1782

I have a Java class which takes Function[String, Void], which is similar to Consumer functional interface. I am calling this Java function from Scala code. As you can see below, I accept function: => Unit on Scala side as it is void equivalent. When I attempt to apply this function in place of Void return type type mismatch happens. Explicit casting of .asInstanceOf[Void] also threw an exception. How do we convert => Unit to => Void?

// Java 
class AcceptFunction {
   public void temp(Function<String, Void> f) {
      f.apply("Hello");
   }
}

// Scala
def temp(f: String => Unit): Unit = {
   new AcceptFunction().temp(new Function[String, Void]() {
   override def apply(t: String): Void = f(t) // <===== error expecting Void instead of Unit
   })
}
3 Answers
Related