-2

Is there a way of passing a function to another function and then executing it?

functionCaller(functionToBeCalled());
0

2 Answers 2

1

In java 8 you can use a method reference or lambda

functionCaller(this::functionToBeCalled);

or

functionCaller(() -> functionToBeCalled());
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, finally a simple way. I'll mark this as answer when I'll be able.
Note that this::functionToBeCalled won't work if you're in a static context.
@Tunaki in that case you need to know the class e.g. MyClass::functionToBeCalled
1

I don't know if I understand very well your question, but effectively you can call a function in param of another function.

You can do this (I suppose your current language is Java):

// if write(...) and getValue() are static method of Writer class  
Writer.write(getValue());

// if write(...) and getValue() can just be used by instanciate an object
Writer writer = new Writer();
String val = writer.getValue();
writer.write(val);

There are basic Java programming lesson. Thanks

1 Comment

The pattern the OP is looking for is the ability to pass in a function to be called, but is not called first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.