【问题标题】:How to save the output of the match statement into variable?如何将匹配语句的输出保存到变量中?
【发布时间】:2020-07-04 15:29:17
【问题描述】:

我有一段代码,我在其中使用了模式匹配,我在所有情况下都使用了 map,我想得到 map 给变量的输出。以下是我的代码:

override def run():List[Option[Student]] =
StudentDataCache.get(surname) match {
  case Some(i) => i.otherSiblings.map(siblings =>
    StudentDataCache.get(siblings) match {
      case Some(i) => Some(i)
      case None=> getStudentFromDatabase(siblings)
    }
  )
  case None =>
    getStudentFromDatabase(surname).get.otherSiblings.map(siblings => StudentDataCache.get(siblings) match {
        case Some(i) => Some(i)
        case None=> getStudentFromDatabase(siblings)
      }
    )
}

case 内的 map 语句的输出都是 List[Option[Student]],有没有办法将它转换为变量,因为我想将此列表转换为单个对象,因为 HystrixCommand 执行输出不支持 List 作为输出.我想将其转换为 StudentListing(val listing: List[Option[Student]])

【问题讨论】:

    标签: scala


    【解决方案1】:

    只是...将它分配给一个值/变量:

    override def run(): StudentListing = {
      val result = StudentDataCache.get(surname) match { /* same code*/ }
      StudentListing(result) // or however you wrap it into a StudentListing...
    }
    

    匹配表达式,与 Scala 中的任何其他表达式一样,被评估为一个值 - 你可以对这个值做任何你想做的事情。

    【讨论】:

    • 我收到此错误:错误:(44, 3) 简单表达式非法开始 val result = StudentDataCache.get(surname) match { ^
    • 您是否在上一行的末尾添加了{,以使其成为run 的多行实现而不是单行?另请参阅:stackoverflow.com/questions/15962563/…
    猜你喜欢
    • 2015-06-08
    • 2019-08-14
    • 2022-11-03
    • 2020-01-23
    • 2014-02-24
    • 2011-11-10
    • 2012-11-07
    • 2015-12-30
    • 2021-10-10
    相关资源
    最近更新 更多