Scala 中非大小写类的模式匹配 [英] Pattern matching over non-case class in Scala

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

问题描述

让我们假设我有一个简单的第三方(即我不能修改它)类定义如下:

Lets assume that I have a plain third party (i.e. I cannot modify it) class defined like:

class Price(var value: Int)

是否可以将此类的实例与某些模式匹配?

Is this possible to match instances of this class with some patterns?

比如我要实现的功能:

def printPrice(price: Price) = {
    // implementation here
}

... 打印 price is {some value} 对于每个具有 value <= 9000price> 的 price在所有其他情况下超过 9000.

... that prints price is {some value} for every price that has value <= 9000 and price is over 9000 in all other cases.

例如调用:

printPrice(new Price(10))
printPrice(new Price(9001))

应该打印:

price is 10
price is over 9000

如何使用模式匹配实现printPrice?

How can I implement printPrice using pattern matching?

推荐答案

考虑过接受 flavian 的解决方案,但自己想出了一个稍微好一点的方案.

Thinked about accepting flavian's solution but came up with slightly better one by myself.

这里是如何实现 printPrice(无需使用包装对象和修改原始类):

Here is how one could implement printPrice (without need to use wrapper objects and modifying original class):

def printPrice(price: Price) = price match {
    case p: Price if (p.value <= 9000) => println("price is " + p.value)
    case p: Price => println("price is over 9000")
}

PS:感谢 flavian 表明您可以在模式中使用 if.对此表示赞同.

PS: credits to flavian for showing that you can use if in pattern. Upvoting your answer for this.

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

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