Problems with Scala variable lookup in Java

Source: Internet
Author: User


In a method of Java/scala, a local variable with the same name as a global variable will overwrite the global variable, but when this variable is referenced before the local variable definition in this method, a different implementation is given in the Java and Scala compilers, first in Java:

➜cat B.java

public class B {
static String name = "Noname";
public static void Main (string[] args) {
SYSTEM.OUT.PRINTLN (name);
String name = "Wang";
}
}

➜java B

Noname
The first row in the Main method references the name is a global variable, and it looks for the variable globally before the definition of the local variable with the same name. And in Scala:

➜cat A.scala
Object A {
Val name:string = "Noname"

def main (args:array[string]) {
println (name)
Val name = "Wang"
}
}

 ➜  Scalac A.scala
A.scala:5: error:forward reference extends over definition of value name
 &N bsp;  println (name)
            ^
One error Found
compile-time error, which takes precedence over the local variable table class inside the method. I'm more receptive to the Java approach, and it's already popular, and I don't know why Scala is doing this, is it intentional or is it an implementation bug?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.