Inside functions self-recursive val's don't seem to be allowed by the compiler. See these examples here:
object Test {
val nats1 : Stream[Int] = 1 #:: (nats1 map (_ + 1)) // OK
def testfun() : Int = {
def nats2 : Stream[Int] = 1 #:: (nats2 map (_ + 1)) // OK
val nats3 : Stream[Int] = 1 #:: (nats3 map (_ + 1)) // Error!
nats2.head
}
def main(args : Array[String]) {
println(testfun)
}
}
That the first definition work isn't very surprising, but what about the third one? Why are self-revursive val's inside functions in Scala not allowed?
That's a pity because sometimes you want to keep a definition local but you want it to be a value and not a def which is evaluated totally every time.
In general that restriction doesn't seem to be necessary. For example the following Haskell-Code works:
module Test where
nats1 :: [Int]
nats1 = 1 : (map (+1) nats1)
testfun :: Int
testfun = let nats2 = 1 : (map (+1) nats2)
in head nats2
main :: IO ()
main = putStrLn $ show testfun