Why is it possible to assign recursive lambdas to non-lazy vals in Scala?

前端 未结 1 893
囚心锁ツ
囚心锁ツ 2021-01-21 18:36

In the following statement the val f is defined as a lambda that references itself (it is recursive):

val f: Int => Int = (a: Int) =>
    if (         


        
相关标签:
1条回答
  • 2021-01-21 19:19

    You probably tried to use this in the REPL, which wraps all contents in an object definition. This is important because in Scala (or better: on the JVM) all instance values are initialized with a default value, which is null for all AnyRefs and 0, 0.0 or false for AnyVals. For method values this default initialization does not happen, therefore you get an error message in this case:

    scala> object x { val f: Int => Int = a => if (a > 10) 3 else f(a+1)+1 }
    defined object x
    
    scala> def x { val f: Int => Int = a => if (a > 10) 3 else f(a+1)+1 }
    <console>:7: error: forward reference extends over definition of value f
           def x { val f: Int => Int = a => if (a > 10) 3 else f(a+1)+1 }
                                                               ^
    

    This behavior can even lead to weird situations, therefore one should be careful with recursive instance values:

    scala> val m: Int = m+1
    m: Int = 1
    
    scala> val s: String = s+" x"
    s: String = null x
    
    0 讨论(0)
提交回复
热议问题