Lambdas in FunctionalInterfaces in Java

shurrok :

I am trying to make use of lambdas in Java but can't understand how it works at all. I created @FunctionalInterface like this:

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

now in my code I use the lambda as here:

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

Next, I want to make use of my function passing it into the constructor of another class and use it like this:

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

Why I need to use it the valueOf() here? I thought that thanks for this I could use just function.getString()?

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

Eran :

Your getString method requires a String argument, so you can't call it without any argument.

That said, your lambda expression ignores that String argument and instead takes data from some person variable (which you didn't show where you declare it).

Perhaps your functional interface should take a Person argument instead:

@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));
}

Alternately, you can remove the argument from your functional interface's method:

@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());
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470838&siteId=1