Scala: where to put @unchecked annotation in foreach

I have the following:

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

I know that a single โ€œcaseโ€ will correspond to all possible values, but I get a warning โ€œthe match is not exhaustiveโ€. The Scala book explains where to put the @unchecked annotation in a normal fully qualified match expression, but not for the form above. How can I annotate above to stop the compiler from complaining?

+3
source share
3 answers

@uncheckedit is defined only for the selector in the matching operation, and not for arbitrary functions. So you could

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

but itโ€™s rather a sip.

, ( PartialFunction):

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

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

, .

+10

@unchecked, x.head x.tail.head x(0) x(1)?

0

Why not add a dummy case if you are sure that this will not happen?

samples.sliding (2).foreach {
  case List (a, b) => printf ("%x %x\n", a.value, b.value)
  case _           => sys.error ("impossible")
}
-2
source

All Articles