Pattern matching over non-case class in Scala

后端 未结 3 2190
天涯浪人
天涯浪人 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

    You can create custom extractor:

    package external {
        class Price(var value: Int)
    }
    
    object Price {
        def unapply(price: Price): Option[Int] = Some(price.value)
    }
    
    def printPrice(price: Price) = price match {
        case Price(v) if v <= 9000 => println(s"price is $v")
        case _ => println("price is over 9000")
    }
    
    printPrice(new Price(10))
    printPrice(new Price(9001))
    

    For case classes compiler generates it automaticaly. I think in your case extractors is overkill, but may be it's only simplified sample.

提交回复
热议问题