scala的@tailrec
註釋是否支持Option.fold
方法?Scala @tailrec與摺疊
@tailrec
def test(a: Int): Int =
if (a > 10)
Option(true).fold(test(a - 1))(_ => test(a - 2))
else
-1
該代碼產生錯誤:
Could not optimize @tailrec annotated method test: it contains a recursive call not in tail position
這個問題可以通過模式匹配,但我覺得fold
看起來清爽多瞭解決。
什麼在這種情況下使用摺疊點?你的方法總是返回-1。你根本不需要遞歸:) – Rumoku
@ Mr.V。這僅僅是一個例子。 – mopdobopot