How to use extractor in polymorphic unapply?

十年热恋 提交于 2019-12-04 07:16:55

Prolly you can try this.. :)

  abstract class Box[T](val v: T)

  object Box {
    def apply(s: String) = new StringBox(s)
    def apply(b: Boolean) = new BooleanBox(b)
    def apply(d: Double) = new DoubleBox(d)

  }

  class StringBox(sValue: String) extends Box(sValue)
  object StringBox {
    def unapply(b: StringBox) = Some(b.v)
  }

  class BooleanBox(sValue: Boolean) extends Box(sValue)
  object BooleanBox {
    def unapply(b: BooleanBox) = Some(b.v)
  }

  class DoubleBox(sValue: Double) extends Box(sValue)
  object DoubleBox {
    def unapply(b: DoubleBox) = Some(b.v)
  }

You can use it as --

  def useCase[T](box: Box[T]) = box match {
    case StringBox("StringBoxxx") => "I found the StringBox!"
    case StringBox(s) => "Some other StringBox"
    case BooleanBox(b) => {
             if (b)  "Omg! its true BooleanBox !"
             else "its false BooleanBox :("
             }
    case DoubleBox(x) => {
                if (x > 3.14)  "DoubleBox greater than pie !"
                else if (x == 3.14) "DoubleBox with a pie !"
                else "DoubleBox less than a pie !"
    }
    case _ => "What is it yaa ?"
  }                                             

  useCase(Box("StringBoxxx")) //> res0: String = I found the StringBox!
  useCase(Box("Whatever !"))  //> res1: String = Some other StringBox
  useCase(Box(true))          //> res2: String = Omg! its true BooleanBox !
  useCase(Box(false))         //> res3: String = its false BooleanBox :(
  useCase(Box(4))             //> res4: String = DoubleBox greater than pie !
  useCase(Box(3.14))          //> res5: String = DoubleBox with a pie !
  useCase(Box(2))             //> res6: String = DoubleBox less than a pie !
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!