3

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 + "'"); };
0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Method

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");

Anonymous class

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

Lambda

But then, the Function could be represented using lambda as simple as :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.