如何在 Scala 中的范围内进行模式匹配? [英] How can I pattern match on a range in Scala?

查看:36
本文介绍了如何在 Scala 中的范围内进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中我可以这样写:

In Ruby I can write this:

case n
when 0...5  then "less than five"
when 5...10 then "less than ten"
else "a lot"
end

如何在 Scala 中做到这一点?

How do I do this in Scala?

最好比使用 if 更优雅.

preferably I'd like to do it more elegantly than using if.

推荐答案

内部模式匹配可以用守卫表示:

Inside pattern match it can be expressed with guards:

n match {
  case it if 0 until 5 contains it  => "less than five"
  case it if 5 until 10 contains it => "less than ten"
  case _ => "a lot"
}

这篇关于如何在 Scala 中的范围内进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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