crazymind
crazymind

Reputation: 169

Does Java allow passing a getter as a method parameter?

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

Upvotes: 0

Views: 2063

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44960

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);

Upvotes: 2

Related Questions