Scala 模式匹配语法

编程入门 行业动态 更新时间:2024-10-10 23:26:27
本文介绍了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 模式匹配语法

本文发布于:2023-11-25 14:58:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630208.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   模式   Scala

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!