Search code examples
functionlambdajava-8functional-interface

What happens if we add different parameter type in a function interface of a lambda expression?


I am learning lambda expressions. I came across a scenario that can be understood by the below code:

Function<Integer,String> fn = (String s)->s;

In the above statement of lambda expression, I know that a function accepts an argument and returns the mentioned type. But why do we mention the argument type ,(here, it is Integer) on the part "Function" whereas the arguments are to be passed inside the "()". I know it is part of the syntax, but I just want to understand the point where it may be useful. It runs even if we pass an different argument type(String)?


Solution

  • First of all the Function you have written is wrong. It should be corrected as below.

    Function<Integer, String> fn = s -> String.valueOf(s);
    

    You can't state a different data type as above, only thing you can state is an integer. Any other data type as the input parameter would result in a compilation failure. The data type of the lambda function parameter is optional and is inferred by the compiler.