Your signature may not be correct. You want your method to take NamedObject as the first argument (so T is NamedObject) and return a string (so now T is a string).
You need two types of type type:
public class Utils { public static <O, T> T nvl(O value, Function<O, T> method, T nullSubstition) { return value == null ? nullSubstition : method.apply(value); } static class NamedObject { String getName() { return "foo"; } } public static void main(String[] args) { NamedObject foo = null; String name = Utils.nvl(foo, NamedObject::getName, "bar"); System.out.println("name = " + name);
An even better signature providing greater flexibility would be
public static <O, T> T nvl(O value, Function<? super O, ? extends T> method, T nullSubstition) { return value == null ? nullSubstition : method.apply(value); }
source share