java - Why class/object name must be explicitly specified for method references? -


when want refer method in current scope still need specify class name (for static methods) or this before :: operator. example, need write:

import java.util.stream.stream;  public class streamtest {     public static int trimmedlength(string s) {         return s.trim().length();     }      public static void main(string[] args) {         system.out.println(stream.of("  aaa  ", "  bb ", " c ")                 .maptoint(streamtest::trimmedlength).sum());     } } 

it's not big problem this, overcrowded static methods class name can quite long. nice if compiler allowed me write ::trimmedlength instead:

public static void main(string[] args) {     system.out.println(stream.of("  aaa  ", "  bb ", " c ")             .maptoint(::trimmedlength).sum()); } 

however java-8 compiler doesn't allow this. me seems quite consistent if class/object name resolved in same manner it's done normal method call. support static imports method references can useful in cases.

so question why such or similar syntax not implemented in java 8? there problems arise such syntax? or not considered @ all?

i can’t speak java developers there things consider:

there kind of method references:

  1. reference static method, e.g. containingclass::staticmethodname
  2. reference instance method of particular object, e.g. containingobject::instancemethodname
  3. reference instance method of arbitrary object of particular type, e.g. containingtype::methodname
  4. reference constructor, e.g. classname::new

the compiler has work disambiguate forms 1 , 3 , sometimes fails. if form ::methodname allowed, compiler had disambiguate between 3 different forms of 3 forms 1 3.

that said, allowing form ::methodname short-cut of form 1 3 still wouldn’t imply equivalent form methodname(…) expression simplename ( argopt ) may refer to

  • an instance method in scope of current class or superclasses , interfaces
  • a static method in scope of current class or superclasses
  • an instance method in scope of outer class or superclasses , interfaces
  • a static method in scope of outer class or superclasses
  • a static method declared via import static

so saying “::name should allowed refer method name(…) may refer to” implies combine possibilities of these 2 listings , should think twice before making wish.


as final note, still have option of writing lambda expression args -> name(args) implies resolving name simple method invocation of form name(args) while @ same time solving ambiguity problem eliminates option 3 of method reference kinds, unless write explicitly (arg1, otherargs) -> arg1.name(otherargs).


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -