Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Case Classes - Are they just structs?

So I just learned about scala case classes, and I'm told they are used to provide a simple wrapper around a bunch of properties so that it's easier to test for equality. But now I have two questions:

  • Is this just the same thing as a struct in C++/C#?
  • Are case classes a value type or a reference type?
like image 577
user3685285 Avatar asked Jun 17 '17 18:06

user3685285


1 Answers

First note that a struct in C++ and a struct in C# are very different things.

  • Structures in C++ are just like regular classes but by default, their members are public. See this post for more on this topic.

  • Structures in C# are value types. When passed as a parameter, they are copied instead of passed via a pointer. This behaviour is similar to a primitive type in Java. This behaviour is the default in C++, with any class or struct.

Your second question has been answered in Eric's answer but the important point is that C# structures are passed completely by value (all their fields are copied) while Java/C# classes are passed via a pointer (that is passed by value). See this famous post if you want the full explanation.

Unfortunately, it is not currently possible to have a true value type in JVM bytecode. You cannot make your own type that will be fully copied everytime you pass it. And the answer is no, case classes aren't value types like C# structures. A JVM language may try to replicate the behaviour of a value type but it will be managed by the GC and passed via a pointer (that is passed by value).

To give a more direct answer, no:

Case classes are like regular classes with a few key differences.

Learn more about them on this page.

like image 67
Winter Avatar answered Oct 11 '22 15:10

Winter