Java method reference not expected here

How exactly do you associate method references for instances with Java 8? Example:

Collections.sort(civs,Comparator.comparing(Civilization::getStrategy.getStrategLevel));

getStrategyinstance Civilizationreturns an instance of an object Strategythat has an instance method getStrategyLevel.

Why Comparator.comparingdoesn't the method return a comparator with it with a functional interface implemented using a lambda expression?

+5
source share
4 answers

In this case you should use lambda, you cannot directly refer to the method link:

Collections.sort(civs, Collectors.comparing(c -> c.getStrategy().getStrategLevel()));

Although, there is a way to use the method link here. Assuming you have a class like

class CivilizationUtils {
    public static Integer getKeyExtractor(Civilization c) {
        return c.getStrategy().getStrategLevel();
    }
}

the problem can be solved as

Collections.sort(civs, Collectors.comparing(CivilizationUtils::getKeyExtractor));
+4

, .

:

  • , ContainingClass::staticMethodName
  • , containingObject::instanceMethodName
  • , ContainingType::methodName
  • , ClassName::new

method reference.

, lambda expression :

Collections.sort(civs, Comparator.comparing(c -> c.getStrategy.getStrategLevel()));

,

public static int getStrategLevel(Civilization c) {
    return c.getStrategy().getStrategLevel();
}

:

Collections.sort(civs, Comparator.comparing(MyClass::getStrategLevel));
+3
Collections.sort(civs,Comparator.comparing(civ -> civ.getStrategy().getStrategLevel()));
+1

,

void m(Predicate<String> stringPredicate)

class Utilities {
  static boolean condition1(String s) { ... }
  static boolean condition2(String s) { ... }
  ...
}

m , , Utilities.condition1 . Java

m(Utilities::condition1)

but no

m(Utilities::condition1.negate())

(unfortunately, violation of referential transparency ), and the compiler complained: "A reference to the Java method is not expected here."

My workaround was to write a method

Predicate<String> not(Predicate<String> p) {
  return p;
}

and then write a call

m(not(Utilities::condition1))

--which is allowed by Java grammar.

0
source

Source: https://habr.com/ru/post/1659937/


All Articles