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

孤街醉人 提交于 2019-12-12 06:23:34

问题


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.


回答1:


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.




回答2:


Void, or more specifically, java.lang.Void, has the following in the documentation:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

In Scala, there's no keyword void, so the Void type is essentially useless in Scala. The closest thing is either a function with no parameters, i.e. def f: Unit = {println(1)} which you can call using f or f(), or the Unit type for functions that don't return anything, as in your example.



来源:https://stackoverflow.com/questions/39735812/how-to-call-a-scala-function-taking-a-value-of-void-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!