First of all, a few of your types are wrong.
As you can see from the error message, def get with no type is assumed to return Unit.
type C does not have isEmpty and get methods
unapply (an extractor) goes from an existing value and returns its parameters in an Option (remember, we’re deconstructing), which is the opposite of you have it.
However, after fixing it to this:
trait t {
type T
val T: {def unapply(t: T): Option[Int]}
def test(a: Any): Unit = a match {case T(i) => println("")}
}
object o extends t {
case class C(i: Int)
type T = C
val T = C//(**)
}
The compiler complains,
/tmp/test.scala:5: warning: abstract type pattern t.this.T is unchecked since it is eliminated by erasure
def test(a: Any): Unit = a match {case T(i) => println("")}
^
/tmp/test.scala:3: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement
val T: {def unapply(t: T): Option[Int]}
^
one warning found
one error found
(The first warning sounds like a compiler bug.)
However, similar to your other question, we can achieve the bigger-picture goal by passing functions around. This works:
trait t {
type T
def extractT: T => Option[Int]
object T {
def unapply(t: T) = extractT(t)
}
def test(a: Any): Unit = a match {case T(i) => println(i)}
}
object o extends t {
case class C(i: Int)
type T = C
def extractT = C.unapply
}
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Hi Naftoli,
One more thing: When I try
object T {
def unapply = extractT(_)
}
I get
an unapply result must have a member `def isEmpty: Boolean
under "T(i)" in
def test(a: Any): Unit = a match {case T(i) => println(i)}
Is that a bug?
TIA,
--Hossein
P.S. How do you get to embed Scala so beautifully in your postings?
Hi Naftoli,
>> object T {
>> def unapply = extractT(_)
>> }
>>
>> I get
>>
>> an unapply result must have a member `def isEmpty: Boolean
>>
>> under "T(i)" in
>>
>> def test(a: Any): Unit = a match {case T(i) => println(i)}
>>
>> Is that a bug?
>
> Unapply usually returns Option.
But, so does also extractT. You wrote:
def extractT: T => Option[Int]
> (As the message indicates it's more flexible, however unless you have a performance reason, Option is the easiest way.)
Sorry, I'm not following. How is that related?
> Markdown Here browser extension.
Cool. It unfortunately is not available on the old version of my
browser which I insist on using. Thank you anyway. :)
Cheers,
--Hossein