3

関数に名前付き引数を使用することを禁止する方法は Scala にありますか?

例:

def func(num: Int, power: Int) = math.pow(num, power)

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

2 に答える 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)
于 2013-09-29T13:59:49.787 に答える
1

Here is what I would suggest:

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.

Unfortunately, it doesn't work that way today, although it's an easy tweak.

The error you'd see today is:

error: deprecated parameter name x has to be distinct from any other parameter name (deprecated or not).

Does it make sense to deprecate the current name of a parameter?

The JavaDoc says:

A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists.

If you can motivate discouraging users from using named arguments when calling a function, then you should be able to deprecate that usage outright.

Maybe there is better wording for the new error:

warning: that parameter is he-who-must-not-be-named!
于 2013-09-29T21:00:51.393 に答える