Pavan
Pavan

Reputation: 77

How to return a Function Interface from a static function?

I am using Function<String, String> inside a static method that is expected to return a value

This accepts an input and returns an output, how to return the value back from the method?

public static String getAnimalName(String name)
{
    Function<String, String> getNameFunc = (inputName)->
    {
        return  inputName.equalsIgnoreCase("cat") ? "dog" : "rat";
    };
    return "";
}

Upvotes: 1

Views: 987

Answers (2)

Neuron
Neuron

Reputation: 5833

What you are doing doesn't make much sense. You are declaring a Function<String, String> inside a function, but not use it. Also I am not sure what the purpose of the parameter is you pass to the function.

Based on your code, I identified three variants that would make sense, but from your question title I would assume you are looking for solution 1.

  1. Return a Function<String, String> and remove the parameter from getAnimalNameFunction

    public static Function<String, String> getAnimalNameFunction() {
        Function<String, String> getNameFunc = (inputName) -> {
            return inputName.equalsIgnoreCase("cat") ? "dog" : "rat";
        };
        return getNameFunc;
    }
    

    and then in some other code..

    Function<String, String> nameConverter = getAnimalNameFunction();
    String name = nameConverter.apply("cow");
    
  2. Keep the parameter, but return a Supplier<String> instead:

    public static Supplier<String> getAnimalNameSupplier(String name) {
        Supplier<String> getNameSup = () -> {
            return name.equalsIgnoreCase("cat") ? "dog" : "rat";
        };
        return getNameSup;
    }
    

    and then in some other code..

    Supplier<String> nameGetter = getAnimalNameSupplier("cow");
    String name = nameGetter.get();
    
  3. Return a String (as you did originally) and remove the intermediate Function<String, String>

    public static String getAnimalName(String name)
    {
        return name.equalsIgnoreCase("cat") ? "dog" : "rat";
    }
    

    and then in some other code..

    String name = getAnimalName();
    

I am not sure which of the three you tried to achieve, but I hope this sheds some light onto the problem.

Upvotes: 3

Abra
Abra

Reputation: 20914

Interface java.util.function.Function contains a single, abstract method named apply. Hence you need to explicitly call that method.

The lambda expression is the actual implementation of the interface.

public static String getAnimalName(String name) {
    Function<String, String> getNameFunc = (inputName) -> {
        return inputName.equalsIgnoreCase("cat") ? "dog" : "rat";
    };
    return getNameFunc.apply(name);
}

Note that you can simplify the lambda expression to

Function<String, String> getNameFunc = inputName -> inputName.equalsIgnoreCase("cat") ? "dog" : "rat";

Upvotes: -1

Related Questions