Does Java support default parameter values?

2018-12-31 18:03发布

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

19条回答
闭嘴吧你
2楼-- · 2018-12-31 18:43

No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.

查看更多
看淡一切
3楼-- · 2018-12-31 18:43

No.

You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.

查看更多
看淡一切
4楼-- · 2018-12-31 18:43

As Scala was mentioned, Kotlin is also worth mentioning. In Kotlin function parameters can have default values as well and they can even refer to other parameters:

fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
    ...
}

Like Scala, Kotlin runs on the JVM and can be easily integrated into existing Java projects.

查看更多
妖精总统
5楼-- · 2018-12-31 18:45

Sadly, no.

查看更多
长期被迫恋爱
6楼-- · 2018-12-31 18:46

I might be stating the obvious here but why not simply implement the "default" parameter yourself?

public class Foo() {
        public void func(String s){
                func(s, true);
        }
        public void func(String s, boolean b){
                //your code here
        }
}

for the default you would ether use

func("my string");

and if you wouldn't like to use the default, you would use

func("my string", false);

查看更多
刘海飞了
7楼-- · 2018-12-31 18:48

It is not supported but there are several options like using parameter object pattern with some syntax sugar:

public class Foo() {
    private static class ParameterObject {
        int param1 = 1;
        String param2 = "";
    }

    public static void main(String[] args) {
        new Foo().myMethod(new ParameterObject() {{ param1 = 10; param2 = "bar";}});
    }

    private void myMethod(ParameterObject po) {
    }
}

In this sample we construct ParameterObject with default values and override them in class instance initialization section { param1 = 10; param2 = "bar";}

查看更多
登录 后发表回答