Does Java support default parameter values?

后端 未结 25 1595
清歌不尽
清歌不尽 2020-11-22 07:07

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

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


        
25条回答
  •  长情又很酷
    2020-11-22 07:24

    Unfortunately, yes.

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

    could be written in Java 1.5 as:

    void MyParameterizedFunction(String param1, int param2, Boolean... params) {
        assert params.length <= 1;
        bool param3 = params.length > 0 ? params[0].booleanValue() : false;
    }
    

    But whether or not you should depend on how you feel about the compiler generating a

    new Boolean[]{}
    

    for each call.

    For multiple defaultable parameters:

    void MyParameterizedFunction(String param1, int param2, bool param3=false, int param4=42) {}
    

    could be written in Java 1.5 as:

    void MyParameterizedFunction(String param1, int param2, Object... p) {
        int l = p.length;
        assert l <= 2;
        assert l < 1 || Boolean.class.isInstance(p[0]);
        assert l < 2 || Integer.class.isInstance(p[1]);
        bool param3 = l > 0 && p[0] != null ? ((Boolean)p[0]).booleanValue() : false;
        int param4 = l > 1 && p[1] != null ? ((Integer)p[1]).intValue() : 42;
    }
    

    This matches C++ syntax, which only allows defaulted parameters at the end of the parameter list.

    Beyond syntax, there is a difference where this has run time type checking for passed defaultable parameters and C++ type checks them during compile.

提交回复
热议问题