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

蓝咒 提交于 2019-12-14 03:56:30

问题


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


回答1:


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)
           ^


来源:https://stackoverflow.com/questions/45358283/tailrec-why-does-this-method-not-compile-with-contains-a-recursive-call-not-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!