1

There are two classes A & B. For example given below:

class A{
    B b;
    B getB(){ return b; }
}

class B{
    String x = "Test";
    String getX(){
       return x;
    }
}

I have object of A in .map(method_refrence_here_for_getX) and I want to call getX so there is any way to do it?

Although i can do like below:

.map(A::getB)
.map(B::getX)

or

.map( a -> a.getB().getX())

But I want to do something like .map(A::B::getX) I know it's absolutely wrong but I want something like this so anyone can help?

Shivang Agarwal
  • 1,825
  • 1
  • 14
  • 19
  • 2
    you can't and you already have listed the only possible options – Eugene Aug 23 '18 at 11:40
  • @Eugene ooops I missed that. – daniu Aug 23 '18 at 11:45
  • @Eugene @Holger Could this not be achieved using a method within class `A` implemented as `String returnXFromA(){ return getB().getX();}` and then referencing it as `A::returnXFromA`? Or maybe I am missing things worse in this kind of approach. – Naman Aug 23 '18 at 11:59
  • @nullpointer of course, but that does not really change the problem on chaining method references – Eugene Aug 23 '18 at 12:01
  • @nullpointer of course, you can create a method of the form `static String someName(A a) { return a.getB().getX(); }` and use a method reference like `MyType::someName`, but that’s *exactly* what you get when using the much simpler lambda expression `a -> a.getB().getX()`. The only difference is that the method will be marked as “Synthetic” on the bytecode level in the lambda expression case. – Holger Aug 23 '18 at 14:12

1 Answers1

1

You simply can't. There is no syntax for that and it's called a method reference (method) and you potentially show a field reference, which is not supported and looks weird to begin with IMO.

There is a difference between the two (map(A::getB).map(B::getX) and map(a -> a.getB().getX())) is that you will save an additional method internally, but this is one tiny optimization and you should really look into what is more readable in your opinion.

Eugene
  • 117,005
  • 15
  • 201
  • 306