Java – Use the lambda for mechanism to find elements in Selenium

Use the lambda for mechanism to find elements in Selenium… here is a solution to the problem.

Use the lambda for mechanism to find elements in Selenium

I

have a code snippet that uses lambda, but I get an error

“target type of a lambda conversion must be an interface”.

Can someone help? My code is as follows:

private By optStarGrade = (strStar) -> { By.xpath("//input[@id='" + strStar + "'"); };

Solution

By is a class, so it cannot be used as the target type of a lambda expression.

Only interfaces with SAM (Single Abstract Methods) can be used as the target type of a lambda expression.

So, if you really want to use lambda, use Consumer<String>

:

private Consumer<String> optStarGrade = (strStar) -> {By.xpath("//input[@id='" + strStar + "'"); };

If you don’t want to ignore the return value of By.xpath, then use Function<String, By>

private Function<String, By> optStarGrade = (strStar) -> By.xpath("//input[@id='" + strStar + "'");

See also Function and Consumer interface for more information.

Related Problems and Solutions