2

Why am I able to redefine a var in subclass with a def and another def. Why compiler doesn't complain?

abstract class Person {
  var age: Int    
}

class Employee extends Person {
  def age = 5 // does not allow override def age = 5, though   

  def age_=(a: Int) = {
    age = a // infinite recursion
  }

}

related to Why it's impossible to override var with def in Scala?

Community
  • 1
  • 1
Adi
  • 727
  • 3
  • 10

2 Answers2

1

The spec says the var declaration is the same as declaring the two methods.

The override keyword is optional as usual.

scala> abstract class B { var x: Int }
defined class B

scala> class C extends B { override def x = 42 ; def x_=(i: Int) = ??? }
defined class C

The linked answer confuses declarations and definitions.

som-snytt
  • 39,429
  • 2
  • 47
  • 129
0

Let's look at the decompiled Java code (using javap your.class):

public abstract class Person {
  public abstract int age();
  public abstract void age_$eq(int);
  public Person();
}

public class Employee extends Person {
  public int age();
  public void age_$eq(int);
  public Employee();
}

As you can see your code results in age being marked as abstract so you are able to implement it.

marteljn
  • 6,446
  • 3
  • 30
  • 43