本文介绍了如何调用带有 Void 类型值的 scala 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何调用这样的scala函数?
How to call such a scala function?
def f(v: Void): Unit = {println(1)}
我还没有在 Scala 中找到 Void 类型的值.
I haven't found a value of Void type in Scala yet.
推荐答案
我相信在 Java 中使用 Void
/null
类似于使用 Unit
>/()
在 Scala 中.考虑一下:
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(); }
既然我们定义了泛型方法 m
,我们还想将它用于 apply
仅对其副作用有用的类(即我们需要返回一些明确的内容)表示没用).void
不起作用,因为它违反了 Fun
合同.我们需要一个只有一个值的类,这意味着删除返回值",它是 Void
和 null
:
class VoidFun extends Fun<Void> {
public Void apply() { /* side effects here */ return null; }
}
So now we can use m
with VoidFun
.
这篇关于如何调用带有 Void 类型值的 scala 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!