2

When inheriting from a Java class with public members, using scala's override modifier raises compilation error like so:

Error:(67, 22) overriding variable userId in class Logon of type String;
 value userId has incompatible type
        override val userId = s.user
                     ^

The java class looks something along the following lines:

public class Logon {
  public String userId = "";
}

and the scala code:

class MyLogon extends Logon {
  override val userId : String = "abc"
}

Removing the modifier results in:

Error:(72, 7) overriding variable userId in class Logon of type String;
 value userId needs `override' modifier
  val userId: String = s.user
      ^

Why is this? Is it a bug? There are related questions e.g. 16607517 but these seem to be changing the visibility of the fields; that's not the case here - they're all public.

Believe this is with scalac-2.10.4.

Community
  • 1
  • 1
Luciano
  • 2,388
  • 1
  • 22
  • 33

2 Answers2

0

It is impossible to override public fields defined in Java because of how it is implemented in Scala:

A public field (val user: String) is represented internally as a combination of private field (say, private val user$1: String) and public accessor method (def user: String = user$1). It is not allowed to override a field with a method, thus the compile error.

There is currently no way to omit the public accessor method generation in Scala, so you'll have to find other ways to implement what you want - either by defining a common trait or interface, or by using another field name, or by wrapping the Java Logon into a Scala Logon with proper superclass constructs.

Scala interoperates extremely well with Java, but the interop is not perfect, unfortunately.

Sergey
  • 2,880
  • 3
  • 19
  • 29
0

You cannot override member variables.

This should not be confused with how scala allows to override val & var which works because scala compiler generates getter and setter methods for them.

codeplay
  • 61
  • 7