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

时间:2018-07-17 16:40:50

标签: scala

我想在使用模式匹配后使用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) )

1 个答案:

答案 0 :(得分:0)

您可以将输入存储为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
}

希望这会有所帮助!