Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6069319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T09:48:36+00:00 2026-05-23T09:48:36+00:00

Consider the following base and derived classes in Scala: abstract class Base( val x

  • 0

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 1: To clarify, I really only want the Base values; the Derived ones just appear to be necessary for initializing the fields of the base class. The example only references them to illustrate the ensuing issues.

Edit 2: Actually, the example would have been clearer if I had used vars instead of vals, since that highlights the problem with values getting changed later on in the base class:

    class Base( var x : Int ) { def increment() { x = x + 1 } }
    class Derived( x : Int ) extends Base( x ) { override def toString = x.toString }

    val derived = new Derived( 1 )
    println( derived.toString )     // yields '1', as expected
    derived.increment()
    println( derived.toString )     // still '1', probably unexpected

Edit 3: 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. It would appear that the Scala compiler could actually have been designed to do this for you, but of course this contradicts the more general rule of “nearer” identifiers (the Derived class’ ‘x’) hiding more remote ones (the Base class’ ‘x’). It seems like a reasonably nice solution would be a modifier like ‘noval’, maybe like this:

    class Base( var x : Int ) { def increment() { x = x + 1 } }
    class Derived( noval x : Int ) extends Base( x ) { override def toString = x.toString }

    val derived = new Derived( 1 )
    println( derived.toString )     // yields '1', as expected
    derived.increment()
    println( derived.toString )     // still '2', as expected
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T09:48:37+00:00Added an answer on May 23, 2026 at 9:48 am

    The idiomatic way to avoid duplicating the field would be to write

    abstract class Base { val x: String }
    
    final class Derived(val x: String) extends Base {
       def toString = x
    }
    

    However, in your version it looks like you actually want a second field, since you have two distinct values. As you correctly point out, giving these fields the same name is likely to lead to confusion.

    Since you don’t actually need the constructor argument outside of the constructor, you could use this approach (a private constructor with a companion module that acts as a factory):

    abstract class Base { val x: String }
    
    final class Derived private (val x: String) extends Base {
       def toString = x
    }
    object Derived {
       def apply(x: String) = new Derived("Base " + x)
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

consider the following python code class Base(object): def __init__(self): self.foo = 5 class Derived(Base):
Consider the following code: class Base { void f() { } }; class Derived:
Consider the following example: class Base(models.Model): myfield = models.CharField() class Derived(Base): pass Now, the
Please consider the following: class base{ base(); ~base(); }: class derived : public base{
Consider the following code: public abstract class Base { public void getAnswer(); } public
Consider the following code: class Base(object): @classmethod def do(cls, a): print cls, a class
Consider the following code: template<int* a> class base {}; int main() { base<(int*)0> test;
Consider following example : public class SomeBusinessLayerService : DataService<MyEntityContainer> { [WebInvoke] void DoSomething(string someParam)
consider the following basic class layout: public class Base : IComparable<Base> { public int
Consider the following class hierarchy: base class Object with a virtual method foo() an

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.