mellow-yellow
mellow-yellow

Reputation: 1810

How to implement IDE's suggestion: "Anonymous new Foo() can be replaced with lambda"

I'm learning anonymous inner classes and lambda functions in Java, especially polymorphism and "passing" interfaces and classes (which apparently means passing an object reference to them, which I'm trying to show below).

I'd like to make the change that my IntelliJ IDEA IDE suggests at poly3 where it says, "Anonymous new Foo() can be replaced with lambda." How do I complete that?

package org.example;

interface Foo {
    String foo();
}

public class Bar implements Foo {
    @Override
    public String foo() {
        return "hi";
    }

    public static void main(String[] args) {
        Object poly1 = new Bar();
        Foo poly2 = new Bar();
        Object poly3 = new Foo() { public String foo() { return "hi"; }}; // Anonymous new Foo() can be replaced with lambda
        Object poly4 = () -> { return "hi"; }; // Error: Target type of a lambda conversion must be an interface
    }
}

Upvotes: 0

Views: 44

Answers (1)

Chaosfire
Chaosfire

Reputation: 6985

When using lambda you need a FunctionalInterface.

Conceptually, a functional interface has exactly one abstract method.

java.lang.Object is not such - it does not have abstract methods. You need to either declare the variable to be Foo

Foo poly = () -> "hi";

or you need to cast your lambda to Foo

Object poly = (Foo) () -> "hi";

Upvotes: 1

Related Questions