inject()方法有强大的累计功能,以闭包作为参数处理一个数据结构并返回一个值。inject()方法的第一个参数是第二个参数(闭包)的立即返回值,无需引入额外的变量就能实现累积计算,例如统计图书馆所有丛书库存,每套丛书有不同套数,每套丛书有不同册数和库存数量,业务模型如下
public class Library {
private List<BookSeries> bookSeriesList;
// getter and setter
}
public class BookSeries {
private int suitNum;
private List<Book> books;
// getter and setter
}
public class Book {
private String name;
private int store;
private double price;
// getter and setter
}
因了inject()的强大累积计算功能,我写了如下测试:
class BookSeriesTest extends Specification {
def "验证丛书总数计算正确"() {
given: "图书馆丛书列表"
def library = new Library(
bookSeriesList: [
new BookSeries(suitNum: 1, books: [
new Book(name: "水浒传(上ÿ