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

  • Home
  • SEARCH
  • 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 8582729
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T21:21:52+00:00 2026-06-11T21:21:52+00:00

I want to do something like this: sealed abstract class Base(val myparam:String) case class

  • 0

I want to do something like this:

sealed abstract class Base(val myparam:String)

case class Foo(override val myparam:String) extends Base(myparam)
case class Bar(override val myparam:String) extends Base(myparam)

def getIt( a:Base ) = a.copy(myparam="changed")

I can’t, because in the context of getIt, I haven’t told the compiler that every Base has a ‘copy’ method, but copy isn’t really a method either so I don’t think there’s a trait or abstract method I can put in Base to make this work properly. Or, is there?

If I try to define Base as abstract class Base{ def copy(myparam:String):Base }, then case class Foo(myparam:String) extends Base results in class Foo needs to be abstract, since method copy in class Base of type (myparam: String)Base is not defined

Is there some other way to tell the compiler that all Base classes will be case classes in their implementation? Some trait that means “has the properties of a case class”?

I could make Base be a case class, but then I get compiler warnings saying that inheritance from case classes is deprecated?

I know I can also:

def getIt(f:Base)={ 
  (f.getClass.getConstructors.head).newInstance("yeah").asInstanceOf[Base]
}

but… that seems very ugly.

Thoughts? Is my whole approach just “wrong” ?

UPDATE I changed the base class to contain the attribute, and made the case classes use the “override” keyword. This better reflects the actual problem and makes the problem more realistic in consideration of Edmondo1984’s response.

  • 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-06-11T21:21:53+00:00Added an answer on June 11, 2026 at 9:21 pm

    This is old answer, before the question was changed.

    Strongly typed programming languages prevent what you are trying to do. Let’s see why.

    The idea of a method with the following signature:

    def getIt( a:Base ) : Unit
    

    Is that the body of the method will be able to access a properties visible through Base class or interface, i.e. the properties and methods defined only on the Base class/interface or its parents. During code execution, each specific instance passed to the getIt method might have a different subclass but the compile type of a will always be Base

    One can reason in this way:

    Ok I have a class Base, I inherit it in two case classes and I add a
    property with the same name, and then I try to access the property on
    the instance of Base.

    A simple example shows why this is unsafe:

    sealed abstract class Base
    case class Foo(myparam:String) extends Base
    case class Bar(myparam:String) extends Base
    case class Evil(myEvilParam:String) extends Base
    
    def getIt( a:Base ) = a.copy(myparam="changed")
    

    In the following case, if the compiler didn’t throw an error at compile time, it means the code would try to access a property that does not exist at runtime. This is not possible in strictly typed programming languages: you have traded restrictions on the code you can write for a much stronger verification of your code by the compiler, knowing that this reduces dramatically the number of bugs your code can contain


    This is the new answer. It is a little long because few points are needed before getting to the conclusion

    Unluckily, you can’t rely on the mechanism of case classes copy to implement what you propose. The way the copy method works is simply a copy constructor which you can implement yourself in a non-case class. Let’s create a case class and disassemble it in the REPL:

    scala>  case class MyClass(name:String, surname:String, myJob:String)
    defined class MyClass
    
    scala>  :javap MyClass
    Compiled from "<console>"
    public class MyClass extends java.lang.Object implements scala.ScalaObject,scala.Product,scala.Serializable{
        public scala.collection.Iterator productIterator();
        public scala.collection.Iterator productElements();
        public java.lang.String name();
        public java.lang.String surname();
        public java.lang.String myJob();
        public MyClass copy(java.lang.String, java.lang.String, java.lang.String);
        public java.lang.String copy$default$3();
        public java.lang.String copy$default$2();
        public java.lang.String copy$default$1();
        public int hashCode();
        public java.lang.String toString();
        public boolean equals(java.lang.Object);
        public java.lang.String productPrefix();
        public int productArity();
        public java.lang.Object productElement(int);
        public boolean canEqual(java.lang.Object);
        public MyClass(java.lang.String, java.lang.String, java.lang.String);
    }
    

    In Scala, the copy method takes three parameter and can eventually use the one from the current instance for the one you haven’t specified ( the Scala language provides among its features default values for parameters in method calls)

    Let’s go down in our analysis and take again the code as updated:

    sealed abstract class Base(val myparam:String)
    
    case class Foo(override val myparam:String) extends Base(myparam)
    case class Bar(override val myparam:String) extends Base(myparam)
    
    def getIt( a:Base ) = a.copy(myparam="changed")
    

    Now in order to make this compile, we would need to use in the signature of getIt(a:MyType) a MyType that respect the following contract:

    Anything that has a parameter myparam and maybe other parameters which
    have default value

    All these methods would be suitable:

      def copy(myParam:String) = null
      def copy(myParam:String, myParam2:String="hello") = null
      def copy(myParam:String,myParam2:Option[Option[Option[Double]]]=None) = null
    

    There is no way to express this contract in Scala, however there are advanced techniques that can be helpful.

    The first observation that we can do is that there is a strict relation between case classes and tuples in Scala. In fact case classes are somehow tuples with additional behaviour and named properties.

    The second observation is that, since the number of properties of your classes hierarchy is not guaranteed to be the same, the copy method signature is not guaranteed to be the same.

    In practice, supposing AnyTuple[Int] describes any Tuple of any size where the first value is of type Int, we are looking to do something like that:

    def copyTupleChangingFirstElement(myParam:AnyTuple[Int], newValue:Int) = myParam.copy(_1=newValue)
    

    This would not be to difficult if all the elements were Int. A tuple with all element of the same type is a List, and we know how to replace the first element of a List. We would need to convert any TupleX to List, replace the first element, and convert the List back to TupleX. Yes we will need to write all the converters for all the values that X might assume. Annoying but not difficult.

    In our case though, not all the elements are Int. We want to treat Tuple where the elements are of different type as if they were all the same if the first element is an Int. This is called

    “Abstracting over arity”

    i.e. treating tuples of different size in a generic way, independently of their size. To do it, we need to convert them into a special list which supports heterogenous types, named HList


    Conclusion

    Case classes inheritance is deprecated for very good reason, as you can find out from multiple posts in the mailing list: http://www.scala-lang.org/node/3289

    You have two strategies to deal with your problem:

    1. If you have a limited number of fields you require to change, use an approach such as the one suggested by @Ron, which is having a copy method. If you want to do it without losing type information, I would go for generifying the base class

      sealed abstract class Base[T](val param:String){
        def copy(param:String):T
      }
      
      class Foo(param:String) extends Base[Foo](param){
        def copy(param: String) = new Foo(param)
      }
      
      def getIt[T](a:Base[T]) : T = a.copy("hello")
      
      scala>  new Foo("Pippo")
      res0: Foo = Foo@4ab8fba5
      
      scala>  getIt(res0)
      res1: Foo = Foo@5b927504
      
      scala>  res1.param
      res2: String = hello
      
    2. If you really want to abstract over arity, a solution is to use a library developed by Miles Sabin called Shapeless. There is a question here which has been asked after a discussion : Are HLists nothing more than a convoluted way of writing tuples? but I tell you this is going to give you some headache

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to do something like this private <T extends List<?>> List<?> getFirstFiveElements(T list)
I want to do something like this: class Dictable: def dict(self): raise NotImplementedError class
i want something like this : public class Order { public Guid OrderID {
Let say I have a class like this: public sealed class Foo { public
I want something like this: abcdab.search(/a/g) //return [0,4] Is it possible?
I want to parse something like this: Hi [{tagname:content}] [{tag1:xnkudfdhkfujhkdjki diidfo now nested tag
I want to do something like this: require 'erb' @var = 'test' template =
I want to run something like this: For a = 0 To 4 For
I want to do something like this in SQL Server: SELECT pt.quantity AS 'QTY'
I want to do something like this in PostgreSQL. I tried this: CREATE or

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.