Equivalent of C++'s std::bind in Java?
bind, c++, functional-programming, java
Solution
This is as close as I think you can get to a line by line translation, `bind` does not map 1:1 to any Java construct;
static void PrintStringInt(String s, int n)
{
System.out.println(s + ", " + n);
}
static void PrintStringString(String s, String s2)
{
System.out.println(s + ", " + s2);
}
interface MyCall {
void fn(String value);
}
public static void main(String[] argv)
{
Vector<MyCall> funcs = new Vector<MyCall>();
funcs.add(new MyCall() {
@Override public void fn(String value) {PrintStringInt(value, 4); }});
funcs.add(new MyCall() {
@Override public void fn(String value) {PrintStringString(value, "bar"); }});
for(MyCall i : funcs){
i.fn("foo");
}
}
Problem
Is there a way to bind parameters parameters to function pointers in Java like you can with std::bind in C++? What would the Java equivalent of something like this be? ``` void PrintStringInt(const char * s, int n) { std::cout << s << ", " << n << std::endl; } void PrintStringString(const char * s, const char * s2) { std::cout << s << ", " << s2 << std::endl; } int main() { std::vector<std::function<void(const char *)>> funcs; funcs.push_back(std::bind(&PrintStringInt, std::placeholders::_1, 4)); funcs.push_back(std::bind(&PrintStringString, std::placeholders::_1, "bar")); for(auto i = funcs.begin(); i != funcs.end(); ++i){ (*i)("foo"); } return 0; } ```