What are the disadvantages to declaring Scala case classes?

后端 未结 5 2053

If you\'re writing code that\'s using lots of beautiful, immutable data structures, case classes appear to be a godsend, giving you all of the following for free with just o

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 05:56

    I am quoting this from Scala cookbook by Alvin Alexander chapter 6: objects.

    This is one of the many things that I found interesting in this book.

    To provide multiple constructors for a case class, it’s important to know what the case class declaration actually does.

    case class Person (var name: String)
    

    If you look at the code the Scala compiler generates for the case class example, you’ll see that see it creates two output files, Person$.class and Person.class. If you disassemble Person$.class with the javap command, you’ll see that it contains an apply method, along with many others:

    $ javap Person$
    Compiled from "Person.scala"
    public final class Person$ extends scala.runtime.AbstractFunction1 implements scala.ScalaObject,scala.Serializable{
    public static final Person$ MODULE$;
    public static {};
    public final java.lang.String toString();
    public scala.Option unapply(Person);
    public Person apply(java.lang.String); // the apply method (returns a Person) public java.lang.Object readResolve();
            public java.lang.Object apply(java.lang.Object);
        }
    

    You can also disassemble Person.class to see what it contains. For a simple class like this, it contains an additional 20 methods; this hidden bloat is one reason some developers don’t like case classes.

提交回复
热议问题