Scala被覆写字段是否存在于虚表中?新手技术咨询
Hey there! Great question—this is a super common point of confusion when you're getting started with Scala, especially if you’re coming from languages where field and method behavior are more distinctly separated. Let’s break this down clearly:
First, a key Scala design detail to keep in mind: every val or var you define in a class automatically generates underlying getter (and setter, for var) methods. This follows the Uniform Access Principle, which lets you access fields and methods with identical syntax.
Overridden val Fields
When you override a val in a subclass (like your class B overriding class A’s x), you’re not just replacing the value—you’re overriding the auto-generated getter method for that val. This getter method does get included in the virtual table, just like your overridden m1 method.
For example, take this code:
class A { val x: Int = 10 def m1(): Unit = println("A's m1") } class B extends A { override val x: Int = 20 override def m1(): Unit = println("B's m1") }
When you call new B().x, you’re actually invoking B’s overridden getter method for x—and this dispatch happens via the virtual table, exactly like calling m1() does. The underlying data storage for x exists in both A and B instances, but the getter method (which is what you interact with when accessing x) is virtual.
Overridden var Fields
The same logic applies to var fields, with one extra layer: vars generate both a getter and a setter method. When you override a var, you’re overriding both of these methods, and both are added to the virtual table.
Note that Scala enforces strict rules here: you can’t override a val with a var (or vice versa) because their underlying method signatures don’t match—val only has a getter, while var has both getter and setter.
A Critical Distinction
It’s important to clarify: the actual data storage (the instance variable holding the value of x) isn’t in the virtual table. The virtual table only contains pointers to methods. But since Scala hides the getter/setter methods behind field syntax, the behavior feels like the field itself is being dispatched virtually.
To wrap up: your intuition about m1 being in the virtual table is spot-on. For overridden fields, it’s their auto-generated getter (and setter, for var) methods that live in the virtual table—giving you that same polymorphic behavior you see with methods.
内容的提问来源于stack exchange,提问作者CodingNow

