如何在Scala中使用if-else为List的元素分配新值



我想在使用if-else进行模式匹配后,从字符串列表中返回元组列表。我是Scala的新手,所以我现在还不知道如何使用模式匹配。

数据:

val foodOrder: List[String] = List(mealOne, mealTwo, mealThree, mealFour, mealFive, mealOne, mealTwo, mealThree)
val mealOne =   ( "Burger and chips", 4.99)
val mealTwo =   ( "Pasta & Chicken with Chips", 8.99)
val mealThree = ( "Pasta & Chicken with Salad", 8.99)
val mealFour =  ( "Rice & Chicken with Chips", 8.99)
val mealFive =  ( "Rice & Chicken with Salad", 8.99)

解决方案:

def stringToItem(order: List[String]): (String, Double) = {
for (order <- orders) {
if(order == mealOne) {
mealOne
stringToItem(foodOrder)
} else if(order == mealTwo) {
mealTwo
stringToItem(foodOrder)
} else if(order == mealThree) {
mealThree
stringToItem(foodOrder)
} else if(order == mealFour) {
mealFour
stringToItem(foodOrder)
} else if(order == mealFive) {
meal
stringToItem(foodOrder)
} else {
noMeal
stringToItem(foodOrder)
}
}
}     

所需结果:List ( ( "Burger and chips", 4.99), ( "Pasta & Chicken with Chips", 8.99), ( "Pasta & Chicken with Salad", 8.99), ( "Rice & Chicken with Chips", 8.99), ( "Rice & Chicken with Salad", 8.99), ( "Burger and chips", 4.99), ( "Pasta & Chicken with Chips", 8.99), ( "Pasta & Chicken with Salad", 8.99) )

您可以将输入存储为String -> (String, Double)的映射。

因此,您的输入将如下所示:-

val mapFoodToPrice: Map[String, (String, Double)] = Map("mealOne" -> ("Burger and chips", 4.99),
"mealTwo" -> ("Pasta & Chicken with Chips", 8.99),
"mealThree" -> ("Pasta & Chicken with Salad", 8.99),
"mealFour" -> ("Rice & Chicken with Chips", 8.99),
"mealFive" -> ("Rice & Chicken with Salad", 8.99))

现在您需要执行以下操作:-

val foodOrder: List[String] = List("mealOne", "mealTwo", "mealThree", "mealFour"
, "mealFive", "mealOne", "mealTwo", "mealThree")

现在,以下是获得所需结果的计算逻辑:-

val result = foodOrder.map { foodName =>
mapFoodToPrice.get(foodName).get
}

希望这能有所帮助!

最新更新