Thursday, March 31, 2022

How to Fix The Target Type of This Expression Must be a Functional Interface Error

This post talks about how to resolve "the target type of this expression must be a functional interface" error while trying to write a lambda expression in Java.

Let's first get some background on what are functional interfaces and lambda expressions in Java; that will help you to get an idea why this error is coming.

Functional Interface in Java

A functional interface is an interface with only one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method).

Refer this post to know more about functional interfaces- Functional Interfaces in Java

Lambda expressions in Java

Lambda expression is an instance of the functional interface and provides implementation of the abstract method defined by the functional interface. Thus the functional interface specifies its target type.

Refer this post to know more about lambda expression- Lambda Expressions in Java 8

As you can see Functional interface is an interface with only one abstract method and lambda expression provides implementation of the abstract method defined by the functional interface.

So this error may come when you have a functional interface which has more than one abstract methods. Let's see it with an example. Here I am trying to write a lambda block which counts the number of words in a string.

interface IMyFunc {
  int func(String n);
  int func1(String n1, String n2);
}

public class FuntionalIntError {
  public static void main(String[] args) {
    String inStr = "Lambdas are a new addition to Java";
    // lamda block assigned to a functional interface reference
    IMyFunc myFunc = (str) -> {
      int c = 0;
      char ch[]= new char[str.length()];
      for(int i = 0; i < str.length(); i++){
        ch[i] = str.charAt(i);
        if(((i > 0) && (ch[i] != ' ') && (ch[i-1] == ' ')) || 
            ((ch[0] != ' ') && (i == 0)))
          c++;
      }
      return c;
    };
    // calling the func method of that functional interface 
    System.out.println("The word count is " + myFunc.func(inStr));
  }
}

This code will give me the same error "The target type of this expression must be a functional interface" because of the fact that functional interface IMyFunc has two abstract methods so lambda expression won't know which of these two methods it is implementing and what is its target type.

How to resolve this error

By now you may have guessed that resolving this error "the target type of this expression must be a functional interface" means functional interface should have only one abstract method. So we need to delete the second method.

interface IMyFunc {
  int func(String n);
  //int func1(String n1, String n2);
}

In order to make sure that the functional interface you write has one and only one abstract method, you can use @FunctionalInterface annotation with your functional interface.

 
@FunctionalInterface
interface IMyFunc {
    int func(String n);
}

With this annotation @FunctionalInterface in place, any attempt to add another abstract method to this functional interface will result in compiler error.

That's all for this topic How to Fix The Target Type of This Expression Must be a Functional Interface Error. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Lambda Expression Examples in Java 8
  2. Lambda Expression as Method Parameter
  3. Lambda Expression And Variable Scope
  4. Method Reference in Java
  5. Java Lambda Expressions Interview Questions And Answers

You may also like-

  1. Java Exception Handling Interview Questions And Answers
  2. Java Multithreading Interview Questions And Answers
  3. How HashMap Works Internally in Java
  4. How to Remove Duplicate Elements From an ArrayList in Java
  5. Creating Custom Exception Class in Java
  6. Multi-Catch Statement in Java Exception Handling
  7. super Keyword in Java With Examples
  8. Word Count MapReduce Program in Hadoop

4 comments:

  1. Hi,
    Please look at my code. Even this throws a compilationerror.

    @FunctionalInterface
    interface TestA{
    int calculate(int x);
    }

    public class TestClass{


    public static void main(String... s) {
    TestClass a = (x) -> x*1; // error here : The target type of this expression must be a functional interface
    int ans = a.calculate(2);
    System.out.println(ans);
    }
    }

    What am i doing wrong?

    ReplyDelete
    Replies
    1. It should be
      TestA a = (x) -> x*1;
      Not TestClass a = (x) -> x*1;
      You are implementing a functional interface through your lambda expression so reference of the interface can hold that implementation.

      Delete
  2. but my error is not like what you say:
    code:
    int a = 1;
    a = () -> 5

    ReplyDelete
    Replies
    1. If you are just writing the mentioned code then obviously it won't work as Lambda expression has to be an implementation of a Functional interface. Change it to
      int a = 1;
      Supplier c = () -> 5;
      a = c.get();
      System.out.println(a);

      Here ()->5 becomes implementation of Supplier functional interface.

      Delete