Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala compiler says unreachable code, why?

I'm new to Scala... Here's the code:

  def ack2(m: BigInt, n: BigInt): BigInt = {
      val z = BigInt(0)
      (m,n) match {
          case (z,_) => n+1
          case (_,z) => ack2(m-1,1) // Compiler says unreachable code on the paren of ack2(
          case _ => ack2(m-1, ack2(m, n-1)) // Compiler says unreachable code on the paren of ack2(
      }
  }

I'm trying to understand that... why is it giving that error?

Note: I'm using Scala Eclipse Plugin 2.8.0.r21376-b20100408034031 ch.epfl.lamp.sdt.feature.group

like image 463
mentics Avatar asked Apr 13 '10 18:04

mentics


People also ask

Why does it say my code is unreachable?

The JavaScript warning "unreachable code after return statement" occurs when using an expression after a return statement, or when using a semicolon-less return statement but including an expression directly after.

Is unreachable code a compile time error?

If any code can not be executable in any of the possible flows, then it is called unreachable code. Unreachable code in java is a compile time error.

How do you find an unreachable code?

While some simple cases of unreachable code can be detected by static analysis (typically if a condition in an if statement can be determined to be always true or false), most cases of unreachable code can only be detected by performing coverage analysis in testing, with the caveat that code reported as not being ...


1 Answers

The z inside the pattern match does not refer to the z you declared outside, it introduces a new variable binding. So the first case will match every possible pair (binding z to the first element of the pair and discarding the second) and the other cases will never be reached.

If you replace z in the pattern with

`z`

it will refer to the existing z and not introduce a new binding, so it will work as you intend. You can also rename z to Z if you don't like the syntax with backticks.

like image 69
sepp2k Avatar answered Oct 02 '22 01:10

sepp2k