Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: where to put the @unchecked annotation in a foreach

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?

like image 599
Alan Burlison Avatar asked Dec 27 '22 01:12

Alan Burlison


1 Answers

@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.

like image 112
Rex Kerr Avatar answered Feb 24 '23 07:02

Rex Kerr