Null aware function invocation operator

前端 未结 2 1190
我在风中等你
我在风中等你 2020-12-10 23:47

In the same way we can have

nullableClassInstance?.method(blah)

Is there a way to do



        
2条回答
  •  有刺的猬
    2020-12-11 00:44

    If you have a Function Object , you can use the call method and send all the parameters to that which works exactly as calling the function. Here , you can use the null aware member access operator.

    void myFun(int a , int b){...}
    
    var myVar = myFun ;
    

    call

    The function myVar will only get called if its not null as shown below.

    myVar?.call( arg1 , arg2 );
    

    apply

    If your function is dynamic or you wish to control which function is being called at run time , you can use the apply static method of Function like so :

    Function.apply(myVar , [arg1 , arg2]);
    

    apply takes the function and a List of parameters that will be sent to the function.

    Read more about call and apply :

提交回复
热议问题