Idiomatic Scala way to deal with base vs derived class field names?
Posted
by
Gregor Scheidt
on Stack Overflow
See other posts from Stack Overflow
or by Gregor Scheidt
Published on 2011-06-29T04:57:57Z
Indexed on
2011/06/29
8:22 UTC
Read the original article
Hit count: 416
Consider the following base and derived classes in Scala:
abstract class Base( val x : String )
final class Derived( x : String ) extends Base( "Base's " + x )
{
override def toString = x
}
Here, the identifier 'x' of the Derived class parameter overrides the field of the Base class, so invoking toString like this:
println( new Derived( "string" ).toString )
returns the Derived value and gives the result "string".
So a reference to the 'x' parameter prompts the compiler to automatically generate a field on Derived, which is served up in the call to toString. This is very convenient usually, but leads to a replication of the field (I'm now storing the field on both Base and Derived), which may be undesirable. To avoid this replication, I can rename the Derived class parameter from 'x' to something else, like '_x':
abstract class Base( val x : String )
final class Derived( _x : String ) extends Base( "Base's " + _x )
{
override def toString = x
}
Now a call to toString returns "Base's string", which is what I want. Unfortunately, the code now looks somewhat ugly, and using named parameters to initialize the class also becomes less elegant:
new Derived( _x = "string" )
There is also a risk of forgetting to give the derived classes' initialization parameters different names and inadvertently referring to the wrong field (undesirable since the Base class might actually hold a different value).
Is there a better way?
Edit: To clarify, I really only want the Base values; the Derived ones just seem necessary for initializing the Base ones. The example only references them to illustrate the ensuing issues. It might be nice to have a way to suppress automatic field generation if the derived class would otherwise end up hiding a base class field.
© Stack Overflow or respective owner