在 Scala 的模式匹配系统中使用比较运算符 [英] Using comparison operators in Scala's pattern matching system

查看:49
本文介绍了在 Scala 的模式匹配系统中使用比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 Scala 中的模式匹配系统进行比较匹配?例如:

Is it possible to match on a comparison using the pattern matching system in Scala? For example:

a match {
    case 10 => println("ten")
    case _ > 10 => println("greater than ten")
    case _ => println("less than ten")
}

第二个 case 语句是非法的,但我希望能够指定当 a 大于时".

The second case statement is illegal, but I would like to be able to specify "when a is greater than".

推荐答案

你可以在模式后添加一个守卫,即一个 if 和一个布尔表达式:

You can add a guard, i.e. an if and a boolean expression after the pattern:

a match {
    case 10 => println("ten")
    case x if x > 10 => println("greater than ten")
    case _ => println("less than ten")
}

请注意,这与将 if after => 放在表面上不同,因为模式 如果守卫不正确,则不会匹配.

Note that this is more than superficially different to putting an if after the =>, because a pattern won't match if the guard is not true.

这篇关于在 Scala 的模式匹配系统中使用比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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