Null aware function invocation operator

怎甘沉沦 提交于 2020-04-28 11:22:14

问题


In the same way we can have

nullableClassInstance?.method(blah)

Is there a way to do

nullableFunctionInstance?(blah)

In other words, is there an operator that checks whether a function instance is not null, if so, invoke the function all in one line?


回答1:


Using the call method, you can achieve what you want with:

nullableFunctionInstance?.call(blah)

There's also the apply method if you want to pass arguments.




回答2:


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 :



来源:https://stackoverflow.com/questions/45022232/null-aware-function-invocation-operator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!