将可选参数传递给函数(它们也是可选的)

Passing optional arguments to a function (where they are also optional)

背景

我在尝试将可选参数传递给另一个函数时遇到问题。被调用的函数也有可选参数,所以我试图让这种可选性一直传播。

我遇到的问题是,由于冷聚变没有 null (or at least not really) 的概念,当省略可选参数时,它实际上不存在。

component accessors=true output=false persistent=false {
    public void function foo(String otherOptional, String optional1,String optional2 ){

        //Other code
        //Other code
        //Other code
        bar(optional1=optional1,optional2=optional2);

    }

    public void function bar(String optional1, String optional2 ){
         //Other code
    }
}

例如在上面的代码中,如果调用 foo 时没有任何参数,我会收到错误消息

Variable OPTIONAL1 is undefined.

The error occurred in D:/web/experimental/OptionalTest.cfc: line 11
9 : 
10 :        //Other code
11 :        bar(optional1=optional1,optional2=optional2);
12 : 
13 :    }

问题

有没有办法将可选参数传递给另一个函数,同时它们也是可选的而不导致错误?

我考虑过的解决方案是:

您需要将它们设为默认值

因此在您的示例中,您可以告诉 CF optional1 等于 "":

component accessors=true output=false persistent=false {
  public void function foo(String otherOptional="", String optional1="",String optional2="" ){

    //Other code
    //Other code
    //Other code
    bar(optional1=optional1,optional2=optional2);

  }

  public void function bar(String optional1, String optional2 ){
     //Other code
     if(len(optional1)){
       //do this
     }

     //etc
  }
}

这是一个涉及 StructKeyExists 的解决方案,但可能与您已经考虑过的方式不同:

bar(
  optional1 = StructKeyExists(arguments, 'optional1') ? arguments.optional1 : JavaCast('null', 0),
  optional2 = StructKeyExists(arguments, 'optional2') ? arguments.optional2 : JavaCast('null', 0)
);