Scala Case Classes - Are They Just Structures?

So, I just found out about scala class classes, and they tell me that they are used to provide a simple wrapper around a lot of properties, to make it easier to check for equality. But now I have two questions:

  • Is it the same as structure in C ++ / C #?
  • Are class classes a value type or a reference type?
+4
source share
3 answers

Firstly, a structin C ++ and structin C # are two different things. So the assignment of case classes in scala coincides with those that 2 things do not make sense.

  • ++ - , . . .

  • # . , . Java. ++, class struct.

, , # ( ), Java/# ( ). . , .

, - JVM. , , . - , case , #. JVM , GC ( ).

, :

.

.

+5

. scala case ... scala.

scala , , .copy .apply .unapply -. .toString , .equals, , ref.

scala.

+5

Scala Java. .

Scala case scala, :

  • ( case , public final Java, case var)
  • equals hashCode,
  • Method applyand unapplycompanion object
  • A toStringmethod showing all constructor values
  • A copymethod

Here is an example:

case class MasterOfTheUniverse(name: String, power: Int)

scala> MasterOfTheUniverse("He-Man", 100).name
res1: String = He-Man

scala> MasterOfTheUniverse("He-Man", 100).power
res2: Int = 100

scala> MasterOfTheUniverse("He-Man", 100).toString
res3: String = MasterOfTheUniverse(He-Man,100)

scala> MasterOfTheUniverse("He-Man", 100) == MasterOfTheUniverse("She-Ra", 90)
res4: Boolean = false

scala> MasterOfTheUniverse("She-Ra", 90) == MasterOfTheUniverse("She-Ra", 90)
res6: Boolean = true

scala> MasterOfTheUniverse("He-Man", 100).copy(name = "He-Manatee")
res7: MasterOfTheUniverse = MasterOfTheUniverse(He-Manatee,100)
+2
source

Source: https://habr.com/ru/post/1679526/


All Articles