【问题标题】:Scala patternmatchingScala 模式匹配
【发布时间】:2021-12-17 06:29:15
【问题描述】:

我在 Scala 中有以下用于模式匹配的代码:

response.flatMap(employee =>
            employee match {
              case e if e.type == Manager => e.headoffice
              case e if e.type == Clerk => e.branch
              case _ => None
            }
          )

这是进行模式匹配的最佳方式吗?能不能更简洁一点?

【问题讨论】:

  • 这里的e.type 是什么?自定义方法?无论如何,您可以删除整个 employee => employee match { 并执行 response.flatMap { case ... }
  • e.type是Employee中的一个字段,枚举类型
  • e.typee 的单例类型。什么 Scala 版本应该编译这个?这整个线程生活在什么奇怪的平行宇宙中,问题和答案都没有任何意义...... O_o??
  • @AndreyTyukin 在任何人中,您只需要使用反引号来修饰 type 字段:scastie.scala-lang.org/BalmungSan/jV1iSWOHQEuiXobySFvpqw/2 - 我不想专注于此,因为 OP 已经提到它是一个字段。 - 无论如何,将我的答案编辑为语法正确。

标签: scala pattern-matching


【解决方案1】:

您可以尝试在type上进行匹配:

response.flatMap(e => e.type match {
    case Manager => e.headoffice
    case Clerk => e.branch
    case _ => None
})

【讨论】:

    【解决方案2】:

    我个人会这样做:

    response.map(e => e -> e.`type`).flatMap {
      case (e, Manager) => e.headoffice
      case (e, Clerk) => e.branch
      case _ => None
    }
    

    【讨论】:

    • 编译在哪个版本上?
    猜你喜欢
    • 2016-05-17
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2015-10-07
    • 2011-05-24
    相关资源
    最近更新 更多