Lifu Huang Lifu Huang - 2 months ago 6
Scala Question

What is the difference between method and field?

In Java, the difference between them is clear. But in Scala, methods can be declared and used without parenthesis. And I also know that Uniform Access Principle is the philosophy that Scala holds. These all make the boundary between field and method vague to a new learner.

At the beginning, I thought

def
and
val
is the boundary between method and field. But it turns out that in Scala, "field" defined in subclass using
val
can override "method" defined in base class using
def
, which seems impossible in any languages I know that distinguish the concepts of field and method.

Thus I wonder:


  1. Whether the concept of "field" does not exist(or is entirely the same thing as parameterless method) in Scala?

  2. If not, what is the boundary between them?


Answer

This is pretty simple. For example for a public val scalac generates private field to hold the value, and a getter.

class A {
  val x = 4
}

in javap you can see

public class A {
  private final int x;
  public int x();
  public A();
}

so if you had

trait T { def x = 1 }

when

class A extends T { val x = 4 }

you are overriding the method x from trait T with a getter x to private field x.

Comments