This is a requirement for which Scala extractors exist. An extractor is a method called unapply that is usually defined in an object (usually it is a companion type of the type in question). It is used to destroy the meaning of its constituents.
Here is an example (pretty far-fetched):
object Extractor1 { def unapply(a: Any): Option[(String, Int)] = Some(a.toString, a.toString.length) } object ExtractorUse { import Extractor1._ def use { "23 skeedo!" match { case Extractor1(str, length) => printf("str=\"%s\"; length=%d%n", str, length) } } }
Using:
scala> ExtractorUse.use str="23 skeedo!"; length=10
If the extractor returns None , an attempt to match it will fail. Similarly, if the arity of the result is not consistent with the varibles of the pattern provided in the case clause.
There is also a copy for extracting unapplySeq sequences. For more information, see "Programming in Scala"
source share