I have a snip code using lambda, but got error
"target type of a lambda conversion must be an interface".
Anyone can help? My code is as follows:
private By optStarGrade = (strStar) -> { By.xpath("//input[@id='" + strStar + "'"); };
By is a class, so it cannot be used as a target type for a lambda expression.
Only interfaces with a SAM (Single Abstract Method) can be used as target types for lambda expressions.
So, if you really wanted to use a lambda, then use a Consumer<String>:
private Consumer<String> optStarGrade = (strStar) -> {By.xpath("//input[@id='" + strStar + "'");};
if you don't want to ignore the returned value from By.xpath then use Function<String, By>
private Function<String, By> optStarGrade = (strStar) -> By.xpath("//input[@id='" + strStar + "'");
See the Function and Consumer functional interfaces for more information.
To simplify what you probably are trying out and to correlate it better you can start off with your current code represented as a method. This method is trying to find a optStarGrade of type By for a given strStar which is a subpart of your XPath, which would look something like:
public static By optStarGradeFunction(String strStar) {
return By.xpath("//input[@id='" + strStar + "'");
}
and then you can create the mechanism By as:
By optStarGrade = findByXPath("XPath");
A similar representation of this method(a.k.a function) would be :
Function<String, By> optStarGradeFunction = new Function<String, By>() {
@Override
public By apply(String strStar) {
return By.xpath("//input[@id='" + strStar + "'");
}
};
and then accessible as
By optStarGrade = optStarGradeFunction.apply("XPath"); // calls the above 'apply' method
But then, the Function could be represented using lambda as simple as :
Function<String, By> optStarGradeFunction = strStar -> By.xpath("//input[@id='" + strStar + "'");