user1861088
user1861088

Reputation: 1733

@tailrec why does this method not compile with 'contains a recursive call not in tail position'?

  @tailrec
  private def loop[V](key: String): V = {
    key match {
      case _ => loop(key)
    }
  }

This method doesn't compile and complains that it 'contains a recursive call not in tail position'. Can someone explain to me what's going on? This error message doesn't make sense to me.

Upvotes: 2

Views: 516

Answers (1)

Denis Makarenko
Denis Makarenko

Reputation: 2928

It compiles ok if the generic type is specified:

import scala.annotation.tailrec

 @tailrec
  private def loop[V](key: String): V = {
    key match {
      case _ => loop[V](key)
    }
  }

I think the error message is misleading in this case.

A simplified version gives a better hint on what's going on:

scala>  @tailrec
     |   private def loop[V](key: String): V = {
     |     loop(key)
     |   }
<console>:14: error: could not optimize @tailrec annotated method loop: it is called recursively with different type arguments
           loop(key)
           ^

Upvotes: 10

Related Questions