3

Currently, I have a UnaryOperator like this

UnaryOperator<Object> defaultParser = obj -> obj;

I don't know if I can use a method reference in these kinds of operation. Example:

UnaryOperator<String> defaultParser = String::toString;

But with the generic way, not just String.

Mani
  • 1,068
  • 3
  • 13
  • 27
Dang Nguyen
  • 1,209
  • 1
  • 17
  • 29
  • `Object::toString` then? Since `toString` is defined on object, that should be what you're looking for in "the generic way". – Silvio Mayolo Dec 05 '18 at 02:10
  • @SilvioMayolo but the Unary maybe receive an object, not just String, and I want that object back. – Dang Nguyen Dec 05 '18 at 02:25
  • `String::toString` is not the same as `obj -> obj`, as the former will throw a `NullPointerException` for `null` input whereas the latter won’t. If that’s not a concern or even intended behavior, you can simply use `UnaryOperator defaultParser = Objects::requireNonNull;` – Holger Dec 05 '18 at 10:49

2 Answers2

4

If you just want to avoid the lambda expression, UnaryOperator has static identity() method:

UnaryOperator<Object> defaultParser = UnaryOperator.identity();

If you specifically want a method reference (why??), you can define a method in your class

public static <T> T identity(T t) {
    return t;
}

Then you will be able to use it as a method reference:

UnaryOperator<Object> defaultParser = MyClass::identity;
Misha
  • 27,433
  • 6
  • 62
  • 78
2

Yes, you can using the UnaryOperator.identity() as:

UnaryOperator<Object> defaultParser = UnaryOperator.identity();

which is defined with a lambda expression as

static <T> UnaryOperator<T> identity() {
    return t -> t;
}
Naman
  • 27,789
  • 26
  • 218
  • 353