【发布时间】:2013-11-17 14:41:01
【问题描述】:
假设我有一个普通的第三方(即我不能修改它)类定义如下:
class Price(var value: Int)
这是否可以将此类的实例与某些模式匹配?
比如我要实现函数:
def printPrice(price: Price) = {
// implementation here
}
...在所有其他情况下,为每个具有value <= 9000 和price is over 9000 的price 打印price is {some value}。
例如调用:
printPrice(new Price(10))
printPrice(new Price(9001))
应该打印:
price is 10
price is over 9000
如何使用模式匹配实现printPrice?
【问题讨论】:
-
(1) 确定
Price有value的公共访问器?因为如果value是私有的,你就无法提取它。 (2) 如果是class Price(val value: Int),为什么不直接println(s"price is ${price.value}")? -
@0__ 感谢您指出 (1)。解决了我的问题。