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
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
You do not have to create a functional interface in order to create lambda function.
Lambda expression provides implementation of functional interface. An interface which has only one abstract method is called functional interface. Java provides an anotation @FunctionalInterface, which is used to declare an interface as functional interface.
A lambda expression (lambda) is a short-form replacement for an anonymous class. Lambdas simplify the use of interfaces that declare single abstract methods. Such interfaces are known as functional interfaces. A functional interface can define as many default and static methods as it requires.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With