Question

I have (simplified from actual code):

class Def[T]

object Fun {
  def unapply[A,B](d: Def[A => B]): Option[A => B] = ???
}

def isFun(d: Def[_]) = d match {
  case Fun(f) => true
  case _ => false
}

This produces a warning:

non-variable type argument A => B in type pattern TypeName.this.Def[A => B] is unchecked since it is eliminated by erasure

I've tried placing @unchecked after Fun(f), but this produces an error; and after f, which doesn't suppress the warning. Is there any way to remove this warning?

Was it helpful?

Solution

I hope I'm wrong, but after browsing the SLS, I don't believe you can apply the annotation in the right place without changing your code.

Since annotations "may apply to definitions or declarations, types, or expressions" (Chapter 11), you need one of those for your annotation application to be syntactically correct. The two most likely candidates here seem to be either a type or an expression. However, looking at Chapter 8 Pattern Matching, it seems

 Fun(f)

i.e. the statement where you need to apply the annotation to, is neither, since it looks like it corresponds to:

 StableId '(' varid ')'

none of which seem to fit the bill for either an expression or a type (or any other valid annotation target).

OTHER TIPS

First, can you change the signature of def isFun(d: Def[_]) to def isFun[A,B](d: Def[A=>B])?

If not, the issue is the type erasure. On the JVM, you can't have this code :

trait Foo {
  def doStuff(xs:List[Int])
  def doStuff(xs:List[Long])
}

At the runtime, you don't have the info of the generics, their type is erased.

So, in your case, the problem is that you can't pattern match against a generic.

Let's see that example in a Scala Worksheet:

object Fun {
    def unapply[A, B](xs: List[Int]): Option[Int] = Some(1)
}

def isFun(d: List[_]) = d match {
    case Fun(f) => true
    case _ => false
} 
//> isFun: (d: List[_])Boolean

isFun(List(1.3)) 
//> res0: Boolean = true

The generic type that we wanted to pattern match against was Int, but it did work with Float.

So, I think that you should change your approach as this pattern matching is obviously going to be a problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top