禁止在Scala中使用命名参数

3
在Scala中,有没有一种方法可以禁止对函数使用命名参数?
例如:
def func(num: Int, power: Int) = math.pow(num, power)

func(3, 2)                   // OK
func(num = 3, power = 2)     // Forbidden

代码检查工具可行吗? - om-nom-nom
尽管用任何方法都可以,但越简单越好,加油! - mosceo
2
不允许使用这种标准语法的原因是什么? - 0__
@0__: 没有任何理由,只是出于好奇。 - mosceo
2个回答

7
您可以使用函数字面量:
val func = (num: Int, power: Int) => math.pow(num, power)

func(3, 2)
func(num = 3, power = 2)  // "error: not found: value num"

(虽然Function2apply仍然有参数名称:)

func(v1 = 3, v2 = 2)

1
这是我的建议:
apm@mara:~$ scalac -deprecation -Xfatal-warnings
Welcome to Scala version 2.11.0-20130923-052707-7d570b54c3 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def f(@deprecatedName('x) x: Int) = 2 * x
f: (x: Int)Int

scala> f(3)
res0: Int = 6

scala> f(x = 4)
<console>:9: warning: naming parameter x has been deprecated.
              f(x = 4)
                  ^
error: No warnings can be incurred under -Xfatal-warnings.

很遗憾,现在还不支持这种方式,尽管这是一个 简单的调整
今天你会看到的错误信息是:
error: deprecated parameter name x has to be distinct from any other parameter name (deprecated or not).

将当前参数名称废弃,是否有意义?

JavaDoc说:

用@Deprecated注释的程序元素是程序员不鼓励使用的元素,通常是因为它具有危险性或者存在更好的替代方案。

如果你能够激励用户在调用函数时不使用命名参数,那么你应该能够彻底废除这种用法。

也许对于新错误有更好的措辞:

warning: that parameter is he-who-must-not-be-named!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接