Scala unapply in features

How can I use unapply in features?

import play.api.libs.json.Json trait Json[T] { implicit val jsonFormat = Json.format[T] } 

Gives a compilation error:

 No unapply function found 

Is there any way to get the compiler to bind T to the case class so that I can use unapply?

+4
source share
1 answer

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"

+1
source

All Articles