Monday, November 30, 2009

Overloaded Unapply

This topic is related to previous posts on matching. I recommend reading some of them as well:
Since an Extactor is just an object with an unapply method it logically follows that an Extractor can have an overloaded unapply method. In other words can have an unapply(String) and an unapply(Int); allowing matching Strings and Ints.
  1. scala> object T{                                                         
  2.      |  def unapply(v:String)= if(v== "s") Some("yay"else None
  3.      |  def unapply(v:Int) = if(v==1) Some("hmmm"else None
  4.      | }
  5. defined module T
  6. scala> 1 match { case T(x) => println(x) }
  7. hmmm
  8. scala> "s" match { case T(x) => println(x) }
  9. yay
  10. scala> object T{                                 
  11.      | def unapplySeq(v:String) = if (v=="x") Some(List(1,2,3)) else None
  12.      | def unapplySeq(v:Int) = if (v==1) Some(List("one","two")) else None
  13.      | }
  14. defined module T
  15. scala>  "x"  match { case T(x,y,z) => println(x,y,z) }
  16. (1,2,3)
  17. scala>  1  match { case T(x,y) => println(x,y) }  
  18. (one,two)

1 comment:

  1. Am I right that this works only when overload can be resolved at compile time?
    So it appears to be somewhat less useful...

    ReplyDelete