The following piece of code does not work:
trait A {
type C
val Extract: {
def unapply(c: C): Option[Int]
}
}
The error is the following:
error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
I wanted to write the above so that I force the user of trait A to define a object or a value which has an unapply
method, so that I can use it in pattern matching.
I found two workarounds thanks to "Parameter type in structural refinement may not refer to an abstract type defined outside that refinement" and Scala: "Parameter type in structural refinement may not refer to an abstract type defined outside that refinement" (see below), but the first one makes inheritance of a trait compulsory, which is not feasible if I try to link to external libraries; and for the second, I loose the possibility to overriding Extract
to put more methods into it.
Workarounds
trait A {
type C
trait Extractable {
def unapply(c: C): Option[Int]
}
val Extract: Extractable
}
trait A {
type C
def extract(c: C): Option[Int]
object Extract {
def unapply(c: C): Option[Int] = extract(c)
}
}
Is there any way (maybe other than structural types) that I can express the idea that the user can implement Extract
the way he wants, provided it has a method unapply
of the requested signature?