Daryoush Mehrtash wrote:
> Looking at the class
>
>
http://lamp.epfl.ch/~linuxsoft/scala/scala-2.4.0/docs/api/scala/Predef$object.Pair$object.html#unapply%28%28a%2Cb%29%29
> <
http://lamp.epfl.ch/%7Elinuxsoft/scala/scala-2.4.0/docs/api/scala/Predef$object.Pair$object.html#unapply%28%28a%2Cb%29%29>
>
> Any idea on how you would use unapply?
In the following...
> scala> val p = Pair(1,"hi there")
> p: (Int, java.lang.String) = (1,hi there)
>
> scala> def rep(p: Pair[Int, String]) = p match {
> | case Pair(n,s) => for (i <- 1 to n) println(s) // Pair.unapply
> is called here; explanation below
> | }
> rep: ((Int, String))Unit
>
> scala> rep(p)
> hi there
>
> scala> rep(Pair(2,"bye"))
> bye
> bye
It took me an hour or so to grok this the first time around... Unapply
is used to implement extractors, namely something that picks apart a
value so that its components can be pattern matched:
val myFoo: Foo = Foo(1,2,3)
myFoo match {
case Foo(a,b,c) => ...
}
"case Foo(a,b,c)" gets translated into Foo.unapply(myFoo), which must
return either:
- Some((1,2,3)) (i.e. an Option[Tuple3[Int,Int,Int]]), where the
Some(...) indicates a match and the Tuple3 therein contains the
extracted values), or;
- None, indicating no match.
HTH,
-0xe1a