Why varargs should be the last in method signature?

前端 未结 5 1896
礼貌的吻别
礼貌的吻别 2020-12-03 01:45

If I try to write a method like below

public void someStuff(Object ... args, String a )

I get this error

The variabl

5条回答
  •  佛祖请我去吃肉
    2020-12-03 02:03

    Because that would make the language unnecessarily complex. Imagine if you also allowed other syntaxes:

    public void someStuff(String a, Object ... args, String b)
    {
    }
    

    Or even:

    public void someStuff(String a, Object ... args, int b, Object ... args2)
    {
    }
    

    This second syntax means a string followed by any number of arguments of type Object, followed by an integer, followed by more objects. Sure you could design a language that could accept things like that, but what if you also wanted to specify that the args2 must contain at least one element, but args can be empty? Why can't we do that too? You could design such a language.

    It boils down to, how complicated do you want the rules to be? In this case they chose a simple option that fulfils the needs.

提交回复
热议问题