Using lambda expression for setting values in Java

136 Views Asked by At

This is a question just for curiosity.

Let's say I have a Java POJO class

@Data
public class MyDto{
  private String id;
}

We can set the values using setId(value), but the question is, can we use lambda in any way to set the value?

I tried using following

public class Service{
  Boolean internalState = false;

  ...
  public void someMethod(String value){
    MyDto dto = new MyDto();
    
    // based on some logic, i want to assign a value (just an example)
    dto.setId((internalState) -> internalState ? value : null);

    // I know i can do this
    if(internalState){
      dto.setId(value);
    }
    else {
      dto.setId(null);
    }
    ...
  }

  ...
}

I tried using above but it my IDE yelled at me with this error "Target type of a lambda conversion must be an interface". I looked for this error and found this has to do something with Function Interface in java.

I know this may not be any actual use case, but to understand Functional Interface deeper, how can we achieve this? Is this even possible?

1

There are 1 best solutions below

0
Partha Sarathi On

Functional Interface in java is an interface that contains exactly one abstract method.

Now, in your code, setId method actually expecting a String value. But when you are writing a lambda function instead, the expected data type is not matching. As in java, lambda function doesn't have a return type, and basically used to implement a functional interface.

Example of Functional interface :

interface Show{
 void display(String name);
}
....
Show s = (name) -> System.out.println(name);
s.display("John Doe");

For your code, you can simply use ternary condition -

dto.setId(internalState ? value : null);