Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this really the way to pass void functions to Scala methods from Java?

I've been playing with Scala/Java interop lately, specifically, calling Scala (2.10.4) code from Java (7). It's been more pleasant than I expected, but a few things puzzle me.

E.g., in scala.runtime I have a nice collection of AbstractFunction abstract classes. But I don't see anything for methods with no return value. E.g., suppose I have the following Scala code:

class MyClass(name: String) {
  def SayWhat(say_fn: String => Unit) = say_fn(name)
}

My understanding is that Java's void is more or less Scala's Unit, so I can pass something vaguely lambda-like with the following Java anonymous class:

import scala.Function1;
import scala.runtime.AbstractFunction1;
import scala.runtime.BoxedUnit;

public class MyProgram {
  public static void main(String[] args) {
    MyClass mc = new MyClass("Dan");

    Function1<String, BoxedUnit> f = new AbstractFunction1<String, BoxedUnit>() {
      public BoxedUnit apply(String s) {
        System.out.println("Why, hello there " + s);
          return null;
      }
    };

    mc.SayWhat(f);
  }
}

This obviously not the prettiest thing, but I appreciate the AbstractFunction stuff, really, compared to what I would have to do otherwise! But is there really no AbstractProcedure or something? Also, why does my "lambda" have to return BoxedUnit?

like image 796
Dan Barowy Avatar asked Apr 25 '14 16:04

Dan Barowy


People also ask

Can I use Scala in Java?

A Scala trait with no method implementation is just an interface at the bytecode level and can thus be used in Java code like any other interface.

Is everything an object in Scala?

Everything is an Object. Scala is a pure object-oriented language in the sense that everything is an object, including numbers or functions. It differs from Java in that respect, since Java distinguishes primitive types (such as boolean and int ) from reference types.


1 Answers

Your function actually has to return BoxedUnit.UNIT, which is the unit in question.

Unit is an AnyVal, not an AnyRef, so it doesn't include null.

It is so much nicer when functions return interesting values.

like image 136
som-snytt Avatar answered Sep 19 '22 21:09

som-snytt