Java中没有默认参数的技术原因 [英] Technical reason for no default parameters in Java

查看:212
本文介绍了Java中没有默认参数的技术原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在四处寻找不包含Java函数默认参数的原因。

I've been looking around to try to find what the reasoning is behind not including default parameters for functions in Java.

我知道有可能使用varargs或通过创建几个接受较少参数的重载函数来模拟行为,然后调用采用所有参数的实函数。但是,这些选项都不符合例如C ++的语法。

I'm aware that it's possible to simulate the behavior, either with varargs or else by creating several overloaded functions that accept fewer parameters, and call the real function that takes all parameters. However, neither of these options match the clarity and ease-of-use of, e.g. C++'s syntax.

有人知道是否有可靠的技术原因会导致类似的情况

Does anyone know if there's a solid technical reason that would make something like

void myFunc(int a=1, int b=2) {...}

在新版本的Java中是不可取的还是不可撤消的?

undesirable or undo-able in a new version of Java?

推荐答案

除了技术上的原因外,我不知道

I am not aware of a technical reason, apart from it being complicated which values are being omitted and which ones are not.

例如,在您的示例中,如果仅传递了一个整数,那么它是<$ c应该默认的$ c> a 或 b ?最可能是 a ,但这确实增加了这种模糊性。

For example, in your sample, if only one integer was passed through then is it a or b that should be defaulted? Most probably a but it does add that level of ambiguity.

一个简单的解决方案是

void myFunc(Integer a, Integer b) {
  if (a == null) a = 1;
  if (b == null) b = 2;

}

是的,它缠绕的时间更长,是的,它隐藏了代码中默认值,而不是方法签名(可以在JavaDoc中显示),但是它确实可以确保一致性。

Yes it is more long winded, and yes it hides the defaulting within the code, rather than the method signature (which could then be shown in JavaDoc), but it does enforce the consistency.

这篇关于Java中没有默认参数的技术原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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