如何调用采用 Void 类型值的 Scala 函数

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

如何调用这样的scala函数?

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

我还没有在 Scala 中找到 Void 类型的值。

Void,或更具体地说,java.lang.Void,在 documentation 中具有以下内容:

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

在 Scala 中,没有关键字 void,所以 Void 类型在 Scala 中基本上是无用的。最接近的是没有参数的函数,即 def f: Unit = {println(1)},您可以使用 ff() 调用,或者 Unit 类型的函数不 return 任何东西,就像你的例子一样。

我认为在 Java 中使用 Void/null 类似于在 Scala 中使用 Unit/()。考虑一下:

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(); }

既然我们定义了泛型方法 m,我们也想将它用于 classes,其中 apply 仅对它的副作用有用(即我们需要 return 明确表明它没用的东西)。 void 无效,因为它违反了 Fun<A> 合同。我们需要一个只有一个值的 class,表示 "drop return value",它是 Voidnull:

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

所以现在我们可以使用 mVoidFun

在 Scala 中不鼓励使用 null 而是使用 Unit(它只有一个值 ()),所以我相信你提到的方法是为了调用来自 Java。为了与 Java 兼容,Scala 具有 null,这是 class Null 的唯一实例。这又是任何引用 class 的子类型,因此您可以将 null 分配给任何引用 class 变量。所以模式 Void/null 也适用于 Scala。