在调用另一个方法时如何使用lambda表达式将方法作为参数传递?

时间:2014-07-25 00:34:09

标签: java parameters lambda java-8

假设我有两种方法void chargeToIndividual(int amount, int account)void chargeToCompany(int amount, int account)。假设我有另一个名为void processSale(String item, Customer c)的方法。我该怎么办?我可以将chargeToIndividualchargeToCompany作为processSale的参数传递给我,我该怎么称呼它?

例如我希望能够做到

if(isIndividual(someCustomer))
{
  processSale(anItem, someCustomer, chargeToIndividual)
}
else if(isCompany(someCustomer))
{
  processSale(anItem, someCustomer, chargeToCustomer)
}

processSale()内,我如何实际致电chargeToIndividualchargeToCustomer()

2 个答案:

答案 0 :(得分:2)

您有两个功能:

void chargeToIndividual(int amount, int account);
void chargeToCompany(int amount, int account);

他们的共同点是,他们都采用两个int参数并返回voidjava.util.function中没有与此形状匹配的功能界面。但是很容易定义我们自己的:

interface IntIntConsumer {
    void accept(int amount, int account);
}

您将按如下方式重写调用代码:

if (isIndividual(someCustomer)) {
    processSale(anItem, someCustomer, MyClass::chargeToIndividual);
} else if (isCompany(someCustomer)) {
    processSale(anItem, someCustomer, MyClass::chargeToCompany);
} else { ... }

如果chargeToIndividualchargeToCustomer是实例方法,则可以使用this::chargeToIndividualthis::chargeToCustomer。另一种方法是将充电功能存储在局部变量中。然后,您只需拨打processSale一次电话:

IntIntConsumer chargeFunc;

if (isIndividual(someCustomer)) {
    chargeFunc = this::chargeToIndividual;
} else if (isCompany(someCustomer)) {
    chargeFunc = this::chargeToCompany;
} else { ... }

processSale(anItem, someCustomer, chargeFunc);

现在在processSale中,对充电功能的调用将如下所示:

void processSale(Item item, Customer customer, IntIntConsumer func) {
    ...
    func.accept(item.getAmount(), customer.getAccount());
    ...
}

当然,我已经假设了amountaccount参数的位置,但我认为你可以理解。

答案 1 :(得分:0)

因为问题是关于使用lambdas:

import java.util.function.Consumer;

public class PlayWithLambdas {

    public void testIsCustomer(Consumer<Chargeable> f) {
        Chargeable customer = new Customer();
        Chargeable company = new Company();
        f.accept(customer); // prints "true"
        f.accept(company);  // prints "false"
    }

    public static void main(String[] args) {
        PlayWithLambdas p = new PlayWithLambdas();
        p.testIsCustomer(chargeable -> {
            System.out.println(chargeable.getType().equals(ChargeableType.CUSTOMER));
        });
    }    
}

interface Chargeable {
    public ChargeableType getType();
}

class Customer implements Chargeable {
    @Override
    public ChargeableType getType() {
        return ChargeableType.CUSTOMER;
    }
}

class Company  implements Chargeable {
    @Override    
    public ChargeableType getType() {
        return ChargeableType.COMPANY;
    }
}

enum ChargeableType {
    CUSTOMER, COMPANY;
}

我希望这位没有任何意义的可怜作家能够帮助你:)