如何调用带有 Void 类型值的 scala 函数 [英] How to call a scala function taking a value of Void type

查看:29
本文介绍了如何调用带有 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 合同.我们需要一个只有一个值的类,这意味着删除返回值",它是 Voidnull:

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

所以现在我们可以使用 mVoidFun.

So now we can use m with VoidFun.

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

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.

这篇关于如何调用带有 Void 类型值的 scala 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆