我正在尝试在Groovy中创建一个Recipe项目,目前我有一个包含配方ID和配方名称的简单配方类,然后我有一个RecipeBook类,它创建一个新的地图然后调用一个方法addRecipe将配方添加到地图中。目前我的食谱只是在地图中覆盖彼此,而不是一个接一个地添加。
class Recipe {
int id
String name
def ingredients
}
class RecipeBook {
// Create a map to store our recipes
def recipeList = [:]
// Use closure to add recipes to the map
def addRecipe = { id,name ->
Recipe recipe = new Recipe(id: id, name: name)
recipeList.put('id',recipe.id)
recipeList.put('name',recipe.name)
// Last element gets returned
recipeList
}
}
RecipeBook recipe = new RecipeBook()
recipe.addRecipe(1, "Chicken Soup")
recipe.addRecipe(2, "Lemon Chicken")
println recipe.recipeList
添加2个食谱后,我的阵列只有2个:柠檬鸡
答案 0 :(得分:1)
您不能将recipe
添加到recipeList
,但是在每次addRecipe
来电时,您设置了recipeList.id
和recipelist.name
。我想而不是
recipeList.put('id',recipe.id)
recipeList.put('name',recipe.name)
你想要像
这样的东西recipeList.put id, recipe