I don’t understand. Why does Scala support override method as field:
abstract class A {
def i: Int;
}
class B extends A {
val i = 123;
}
val obj:A = new B();
println(obj.i)
Method i is as field i. Why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One quick way to see what’s going on here is to compile this code and use
javapto inspect the resulting classes. Here we get the following forA:And for
B(with-p, so we see any private members):So the
valjust ends up as a private field with a getter—much like what you’d write in idiomatic Java, although the naming convention is different (and isn’t really a convention, since the compiler handles it for you).