Pattern matching over non-case class in Scala

后端 未结 3 2184
天涯浪人
天涯浪人 2020-12-15 11:42

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 m

3条回答
  •  爱一瞬间的悲伤
    2020-12-15 12:26

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

    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: credits to flavian for showing that you can use if in pattern. Upvoting your answer for this.

提交回复
热议问题