class、object、case class、case object区别!

First, understand:

  1. class is similar to class in Java;
  2. object Scala cannot define static members, use the definition of singleton objects instead;
  3. A case class is called a sample class, which is a special class that is often used for pattern matching.

1. The relationship between class and object:

  1. Singleton objects cannot take parameters, but classes can;
  2. When the object can be the same as the class name, the object is called the companion object, and the class is called the companion class;
  3. Classes and companion objects can mutually access their private properties, but they must be in a source file;
  4. The class will only be compiled, not executed. To be executed, it must be in Object.

2. The difference between case class and class:

  1. New can be added or not used when initializing, but new must be added to ordinary classes;
  2. The equals and hashCode methods are implemented by default;
  3. It is serializable by default, and Serializable is implemented;
  4. Automatically inherit some functions from scala.Product;
  5. The case class constructor parameters are public and can be accessed directly;
  6. The case class cannot modify the attribute value by default;
  7. The most important function of the case class is to support pattern matching, which is also an important reason for defining the case class.

3. The difference between case class and case object:

  1. There are parameters and no parameters in the class. When the class has parameters, use case class. When the class has no parameters, use case object.

4. When a class is called a case class, scala will help us do the following things:

  1. If the parameter in the constructor is not declared as var, it is of type val by default, but it is generally not recommended to declare the parameter in the constructor as var;

  2. The companion object is automatically created, and the sub-apply method is implemented for us in it, so that we can not directly display the new object when we use it; if the apply method is a method, I don’t understand what it does. . . It's a bit winding. But it is probably like a java constructor, accepting construction parameters into an object.

  3. The companion object will also help us implement the unapply method, so that the case class can be applied to pattern matching; the unapply method is mainly used in pattern matching, accepting an object, and extracting the corresponding value from the object.

  4. Implement your own toString, hashCode, copy, equals methods

  5. Otherwise, the case class is no different from other ordinary scala classes

To sum it up: this one is still a bit ignorant. Continue to struggle tomorrow.

Guess you like

Origin blog.csdn.net/qq_42658739/article/details/106724994