Scala:具有可重用条件的模式匹配 [英] Scala: pattern matching with reusable condition

查看:56
本文介绍了Scala:具有可重用条件的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这种模式匹配的情况:

Considering this case of pattern matching:

foo match {
    case x if expensiveCalculation(x).nonEmpty => // do something with expensiveCalculation(x)
...
}

是否可以在 => 之后标记"或重复使用 expensiveCalculation(x)?

is it possible to "label" or reuse the expensiveCalculation(x) after the =>?

理想情况下,我期待的是:

Ideally I was expecting something like:

foo match {
        case x val ec = expensiveCalculation(x); if ec.nonEmpty => // do something with ec
    ...
    }

推荐答案

您可以为 x 的类型编写一个提取器(这里假设为 InputType):

You can write an extractor for the type of x (here assuming InputType):

object Expensive {
  def unapply(x: InputType): Option[OutputType] = expensiveCalculation(x)
}

现在,您可以在模式匹配中使用它:

Now, you can use it in your pattern matching:

fooList match {
  case _ :: Expensive(output) :: _ => ...
  case _ :: x :: _ => ...
}

但是,如果您为许多计算执行此操作(每次都需要定义一个提取器),那么这是一种很麻烦的方法来执行您想要的操作.

However, this is a cumbersome way to do what you want, if you do this for many calculations (you need to define an extractor every time).

您可以通过定义以下内容来一劳永逸:

You might do it once and for all by defining the following:

case class Comput[-A, +B](f: A => Option[B]) {
  def unapply(a: A): Option[B] = f(a)
}

现在,您可以按如下方式使用它:

Now, you can use it as follow:

val intString = "10"
val IntOf = Comput[String, Int](s => Try(s.toInt).toOption)

intString match {
  case IntOf(x) => x
  case other => 0
} // returns 10: Int

但是,在模式匹配中使用 IntOf 之前,您不能免除定义它(编译器解析器似乎丢失了).

However, you cannot dispense from defining IntOf before using it in pattern matching (the compiler parser seems to be lost).

这篇关于Scala:具有可重用条件的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆