Java Lambda Method Reference - Clarity Required

Viewed 60

I am getting error while passing lambda method refrence, with type incompatibilty. while calling the FUnctional Interface method, code compile perfectly fine and substituting the Concrete objects. While Passing method reference it throwing type incompatibility. Please clear my misunderstanding

public interface ParsingFileFunction {
    public <K,T> K getMessage(T inputMessage);
}

public class FileUtility {
    public static Messages readMessage(File kingMesaages){
        //some process here
        return messages; //of Messages type
    }
}
public class SomeController{
    @Autowired
    SomeService someService;
    public void parse(File kingMessage) {
        //compiler error -- The type FileUtility does not define readMessage(T) that is applicable here
        Messages kingdomMessages = someService.getMessage(FileUtility::readMessage,kingMessage);
    }
}

@Service
public class SomeService{
    public Messages getMessage(ParsingFileFunction parse,File file) {
        //this compiles perfectly fine as expected
        return parse.getMessage(file); 
    }
}
1 Answers

Java can't check the correct types because they are not part of the interface definition but part of the method definition. It works using the following adjustments:

ParsingFileFunction.java

public interface ParsingFileFunction<K, T> {
    K getMessage(T inputMessage);
}

Note that the types have been moved to the interface definition.

SomeService.java

import org.springframework.stereotype.Service;

import java.io.File;

@Service
public class SomeService {

    public Messages getMessage(ParsingFileFunction<Messages, File> parse, File file) {
        return parse.getMessage(file);
    }
}

Note the explicit types in the declaration of file.

Related