3

I have the following interface:

public interface Mapper {
    public <T> T map(T element);
}

and when I do Mapper mapper = (int n) -> n*2; I get the problem:

Illegal lambda expression: Method map of type Mapper is generic

What am I missing here? How is it possible to create a generic method to use in lambda expression?

THE Waterfall
  • 645
  • 6
  • 17

1 Answers1

2

You should change your definition to

public interface Mapper<T> { // type bound to the interface
    T map(T element);
}

and then use it as :

Mapper<Integer> mapper = element -> element * 2; // notice Integer and not 'int' for the type

which can also be written as :

Mapper<Integer> mapper = (Integer element) -> element * 2;
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Yeap, thanks, this actually works. But why can't I declare type parameter in method level like in `.toArray` method in List interface? ` T[] toArray(T[] a)` – THE Waterfall Jan 07 '19 at 01:35
  • @THEWaterfall you can but then your implementation of the abstract method `map` would require inferring the type/casting to an Integer to perform the operation `*2` which is where you would have to always write an anonymous class to represent the complete implementation and not just lambdas... and I am not sure if toArray could be used as lambda, have you read somewhere that `toArray` being used in lambdas? – Naman Jan 07 '19 at 01:38
  • But if I do `(Integer element) -> element * 2`. Don't I already explicitly type cast to an Integer? I am not sure about `toArray` being used in lambdas but I am just confused that it's impossible to make a generic method using method level type parameter in order to use in lambdas. – THE Waterfall Jan 07 '19 at 01:41
  • @THEWaterfall Actually, that's what the specifications linked in the duplicate question(parent) states. And no the type is not casted to Integer if its bound at method level. – Naman Jan 07 '19 at 01:45