Discussion:
Scala cannot resolve overloaded unapply
mjuric
2011-10-28 21:12:56 UTC
Permalink
I am very new to Scala and maybe could someone explain why I get
"cannot resolve overloaded unapply"-error in this:

case class Element (
id: String
)

object Element {
def unapply(id: String): Option[Element] = Some(Element(id))
}

Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java
1.6.0_26)
Alex Cruise
2011-10-28 21:20:22 UTC
Permalink
Post by mjuric
I am very new to Scala and maybe could someone explain why I get
case class Element (
id: String
)
object Element {
def unapply(id: String): Option[Element] = Some(Element(id))
}
That's more like apply, not unapply. It's constructing an instance from
value(s), rather than extracting value(s) from an instance.

The auto-generated unapply method would unconditionally extract the
property, returning it as an Option[T]. For a Product with more than one
element, the return type is Option[Tuple*n*[T*1*,...T*n*]].

def unapply(el: Element): Option[String] = Some(el.id)


The auto-generated apply method would look like this:

def apply(id: String) = new Element(id)


HTH,

-0xe1a
mjuric
2011-10-28 22:27:07 UTC
Permalink
I see, Thanks. It actually fits with the book explanation. I am just
confused about a Lift example, which seemed to do something similar as
I was. While I could compile the Lift example, I could not get my
variation to work. I still have to study extractors more closely since
the following works:

case class Element(
id: String
)

object Element {

def unapply(id: String): Option[Element] = Some(Element(id))

def unapply(in: Any): Option[String] = in match {
case f: Element => Some(f.id)
case _ => None
}
}
Post by mjuric
I am very new to Scala and maybe could someone explain why I get
case class Element (
 id: String
)
object Element {
 def unapply(id: String): Option[Element] = Some(Element(id))
}
That's more like apply, not unapply.  It's constructing an instance from
value(s), rather than extracting value(s) from an instance.
The auto-generated unapply method would unconditionally extract the
property, returning it as an Option[T].  For a Product with more than one
element, the return type is Option[Tuple*n*[T*1*,...T*n*]].
def unapply(el: Element): Option[String] = Some(el.id)
def apply(id: String) = new Element(id)
HTH,
-0xe1a
Loading...