0

No Lambda, Predicate, Interface. Just a regular class with a regular getter. For example:

public int getWeight(){return weight;}

public int convertToLbs(int weight){some code here ...}


someObject.convertToLbs(someObject.getWeight())//valid???

Thanks

crazymind
  • 169
  • 2
  • 11
  • 5
    have you tried it? – jhamon Jan 16 '19 at 16:27
  • 2
    You’re not passing a method reference in your example, you’re calling a getter and passing the returned value. – vandench Jan 16 '19 at 16:28
  • 1
    Yes, its allowed since it returns int its as good as passing integer to a method. – Santosh Jan 16 '19 at 16:29
  • van dench Thanks. Java use pass by value. Not sure what is method reference? Can you elaborate? – crazymind Jan 16 '19 at 16:29
  • should be very easy to test... anyway, your call is kind of the same as `int w = someObject.getWeight(); someObject.convertToLbs(w);` – user85421 Jan 16 '19 at 16:32
  • A method reference is where you pass a literal reference to a method, it is usually stored into an interface (with only one function) in Java. You can also pass a lambda or abstract class. What this means is that the receiver can choose when to call the function, this is useful for streams. A simple example would be that you have a method that receives a method which accepts two integers and returns an integer, you could pass a function that multiplies the values, adds the values, or does basically anything to the values, you just don’t know what 2 values you will be getting. – vandench Jan 16 '19 at 16:33
  • van dench Thanks! – crazymind Jan 16 '19 at 16:36

1 Answers1

2

Your current syntax is valid but you are passing the weight value because Java is pass-by-value.

To pass a method reference for something that returns int you can use IntSupplier:

public int getWeight() { return weight; }
public int convertToLbs(IntSupplier s) { int w = s.getAsInt(); ... }

someObject.convertToLbs(someObject::getWeight);
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111