zyxue zyxue - 1 year ago 97
Scala Question

How to call a scala function taking a value of Void type

How to call such a scala function?

def f(v: Void): Unit = {println(1)}

I haven't found a value of Void type in Scala yet.

Answer Source

I believe using Void/null in Java is similar to using Unit/() in Scala. Consider this:

abstract class Fun<A> {
  abstract public A apply();

class IntFun extends Fun<Integer> {
  public Integer apply() { return 0; }  

public static <A> A m(Fun<A> x) { return x.apply(); }

Now that we defined generic method m we also want to use it for classes where apply is only useful for its side effects (i.e. we need to return something that clearly indicates it's useless). void doesn't work as it breaks Fun<A> contract. We need a class with only one value which means "drop return value", and it's Void and null:

class VoidFun extends Fun<Void> {
  public Void apply() { /* side effects here */ return null; }  

So now we can use m with VoidFun.

In Scala usage of null is discouraged and Unit is used instead (it has only one value ()), so I believe the method you mentioned was intended to be called from Java. To be compatible with Java Scala has null which is the only instance of a class Null. Which in turn is a subtype of any reference class, so you can assign null to any reference class variable. So the pattern Void/null works in Scala too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download