Scala 模式匹配语法 [英] Scala pattern matching syntax

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

问题描述

我最近一直在玩 Scala 模式匹配,想知道是否有办法在 case 语句中创建提取器.以下代码有效,但您必须先定义提取器并将其分配给一个 val:

I've been playing with scala pattern matching recently and was wondering whether there is a way to create an extractor inside of the case statement. The following code works, but you have to define the extractor first and assign it to a val:

val Extr = "(.*)".r
"test" match {
  case Extr(str) => println(str)
}

我想做的事情,或者我想让别人确认的事情是不可能的,是这样的:

What I would like to do, or what I would like someone to confirm is impossible, is something like this:

"test" match {
  case ("(.*)".r)(str) => println(str)
}

如果 Scala 团队的任何人正在阅读此内容:实施此内容是否可行?

In case anyone from the scala team is reading this: Would it be feasible to implement this?

推荐答案

不幸的是,这是不可能的,我认为没有办法简化您的第一个示例.

Unfortunately it is not possible and I see no way to simplify your first example.

case 语句后面必须跟一个模式.Scala 语言规范在第 8.1 节中显示了模式的 BNF.模式的语法非常强大,但实际上只是一个模式,不允许有方法调用或构造函数.

The case statement has to be followed by a Pattern. The Scala Language Specification shows the BNF of patterns in section 8.1. The grammar of patterns is quite powerful, but is really just a pattern, no method calls or constructors are allowed there.

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

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