Question

I have the following:

samples.sliding(2).foreach{case List(a, b)=> printf("%x %x\n", a.value, b.value)}

I know that the single 'case' will match all the possible values but I get a 'match is not exhaustive' warning. The Scala book explains where to put the @unchecked annotation on a normal fully-specified match expression, but not for the form above. How do I annotate the above to stop the compiler from complaining?

Was it helpful?

Solution

@unchecked is only defined for the selector in a match operation, not for arbitrary functions. So you could

foreach{ x => (x: @unchecked) => x match { case List(a,b) => ... } }

but that is rather a mouthful.

Alternatively, you could create a method that unsafely converts a partial function to a complete one (which actually just casts to the function superclass of PartialFunction):

def checkless[A,B](pf: PartialFunction[A,B]): A => B = pf: A => B

and then you can

samples.sliding(2).foreach(checkless{
  case List(a,b) => printf("%x %x\n", a.value, b.value)
})

and you don't have any warnings because it was expecting a partial function.

OTHER TIPS

No idea about @unchecked, but why not just call x.head and x.tail.head or x(0) and x(1)?

Why don't you add an dummy case, if you're sure it will never happen?

samples.sliding (2).foreach {
  case List (a, b) => printf ("%x %x\n", a.value, b.value)
  case _           => sys.error ("impossible")
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top