Lambdas in FunctionalInterfaces in Java

I am trying to use lambdas in Javabut cannot figure out how this works at all. I created @FunctionalInterfaceas follows:

@FunctionalInterface
public interface MyFunctionalInterface {
    String getString(String s);
}

now in my code i use lambdaas here:

MyFunctionalInterface function = (f) -> {
    Date d = new Date();
    return d.toString() + " " + person.name + " used fnc str";
};

Next, I want to use mine function, passing it to the constructor of another class, and use it as follows:

public SampleClass(MyFunctionalInterface function) {
    String tmp = "The person info: %s";
    this.result = String.format(tmp, function.getString(String.valueOf(function)));
}

Why do I need to use it valueOf()here? I thought thanks for this, could I use only function.getString()?

Output: Tue Sep 19 11:04:48 CEST 2017 John used fnc str

+6
source share
1 answer

Your method getStringrequires an argument String, so you cannot invoke it without any arguments.

, - String person ( , ).

, person:

@FunctionalInterface
public interface MyFunctionalInterface {
    String getString(Person p);
}

MyFunctionalInterface function = p -> {
    Date d = new Date();
    return d.toString() + " " + p.name + " used fnc str";
};

public SampleClass(MyFunctionalInterface function, Person person) {
    String tmp = "The person info: %s";
    this.result = String.format(tmp, function.getString(person));
}

:

@FunctionalInterface
public interface MyFunctionalInterface {
    String getString();
}

MyFunctionalInterface function = () -> {
    Date d = new Date();
    return d.toString() + " " + person.name + " used fnc str";
};

public SampleClass(MyFunctionalInterface function) {
    String tmp = "The person info: %s";
    this.result = String.format(tmp, function.getString());
}
+5

All Articles