Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Can't use lambda for self made interface - Target type of lambda conversion must be an interface

I have the following code:

public interface Logic
{

    boolean logicAccesscible();
}


public class LocationLogic implements Logic
{
    @Override
    public boolean logicAccesscible()
    {
        return true;
    }
}

But when I try to use a lambda to create a LocationLogic object it simply won't work.

    l.setLocationLogic(new LocationLogic()
    {
        @Override
        public boolean logicAccesscible()
        {
            return false;
        }
    });

that snipet works, but

l.setLocationLogic(() ->
    {
        return false;
    });

Gives me the error of "Target type of lambda conversion must be an interface"

And yes, I've tried to use:

l.setLocationLogic((LocationLogic) () -> {return false;});
like image 793
Kishirada Avatar asked Mar 04 '26 12:03

Kishirada


1 Answers

You get this error because, you can only create lambdas from functional interfaces, which just means an interface with exactly one abstract method.

Now your setLocationLogic expects a LocationLogic (a class) and java forbids the creation of lambdas from classes. thats why your first snippet works, but your second doesn't.

Either change the signature of setLocationLogic to setLocationLogic(Logic logic).

Or maybe create a constructor in LocationLogic which accepts a boolean, which you then return in the implemented function:

public class LocationLogic implements Logic{
    private final boolean accessible;

    public LocationLogic(boolean accessible){
        this.accessible = accessible;
    }

    public boolean logicAccessible(){
        return accessible;
    }
}

That way you could use it like:

l.setLocationLogic(new LocationLogic(false));
like image 161
Lino Avatar answered Mar 07 '26 03:03

Lino