In this article, we will show how to use a function when your code expects an interface, and vice versa.
From Function to Interface
If you need to convert a function to a single-method interface, then you can define a method on the function type directly.
For instance, let’s say that you have the following function:
| |
And you need an object implementing this interface in order to user the userCode function.
| |
The following code creates a user-defined function type and defines a method MethodName on that type:
| |
Which let’s you easily convert between the function and the interface as follows:
| |
From Interface to Function
To use a single-method interface where a function is expected, simply pass the interface’s method:
Let’s say that you have an object implementing this interface:
| |
And you want to use funcUserCode that requires a function object:
| |
Then, you can directly pass the method as argument:
| |
Or you can wrap the method call in an anonymous function:
| |