Higher-order, partial function — where to place @unchecked annotation?

354 views Asked by At

I've a piece of code for which I get a "match may not be exhaustive" warning from Scala 2.13.4, and I'd like to suppress that warning with the @unchecked annotation. Unfortunately, all my attempts of inserting @unchecked merely resulted in syntax errors.

Here's a mercilessly simplified version of the original code:

def foo(xs: Seq[Int], n: Int)(f: (Seq[Int], Int) => Int): Int = f(xs, n)
    
foo(Seq(1,2), 0) { case (Seq(a,b), c) => a + b + c }

Question: Where do I syntactically put @unchecked at call site in order to suppress the warning?

P.S. I'd like to suppress the warning, not start a discussion of whether or not that is evil ;-)

3

There are 3 answers

1
Paul Brown On

Not sure if I've understood this correctly but have you tried something like this:

def pie(x: Option[String]) =
(x: @unchecked) match {
  case Some(v) => v
}

The warning is removed (for me) with this syntax

3
Tomer Shetah On

I am not really sure what is that good for, but I think this is the maximum unchecked you can do in the code in the question:

def foo(xs: Seq[Int @unchecked] @unchecked, n: Int @unchecked)(f: (Seq[Int @unchecked] @unchecked, Int @unchecked) => Int @unchecked): Int @unchecked = {
  f(xs, n)
}

println(foo(Seq(1,2), 0) {
  case (Seq(a: Int @unchecked,b: Int @unchecked), c: Int @unchecked) => a + b + c
})

unchecked in Scaladoc. Code run at Scastie.

2
sparker On

I didn't get warnings after enabling "unchecked" in compiler options in IntelliJ. It's not scalastyle, is it? I appreciate your example is contrived. Does either of these approaches work for you?

Option 1: Defining your curried function as a PartialFunction

def foo(xs: Seq[Int], n: Int) (f: PartialFunction[(Seq[Int], Int), Int]): Int = 
    if(f.isDefinedAt(xs, n))
        f(xs, n)
    else 0

Option 2: Converting your case statement to a match expression?

foo(Seq(1,2), 0) {
  (_:(Seq[Int], Int) @unchecked) match
  {
    case (Seq(a, b), c) => a + b + c
  }
}