[Scala] Scala基础知识
Object
- An object is a type of class that can have no more than one instance, known in object-oriented design as a singleton. Instead of creating an instance with a
new
keyword, just access the object directly by name. - Objects provide similar "static" and "global" functionality but decouple them from instantiable classes.
- Objects do not take any parameters (they are automatically instantiated), but you can define the same fields, methods, and internal classes as you can with regular classes. 不需要传入任何参数,因为你可以直接访问object里面的内容
Companion Object
- A companion object is an object with the same name as a class or trait and is defined in the same source file as the associated file or trait.
- A companion object differs from other objects as it has access rights to the class/trait that other objects do not.
- A companion object is as a factory for creating instances of the class.
- An analog to a companion object in Java is having a class with static methods. In Scala you would move the static methods to a Companion object.
- When a case-class is declared a companion object is created for the case-class with a factory method that has the same signature as the primary constructor of the case class
NOTE: Because the companion object and the class must be defined in the same source file you cannot create them in the interpreter.
Case Class
Case classes differ from regular classes in that they get:
- pattern matching support 支持模式匹配
- default implementations of
equals
andhashCode 默认实现equals和hashCode
- default implementations of serialization 默认实现序列化
- a prettier default implementation of
toString
, and 默认更好实现toString - the small amount of functionality that they get from automatically inheriting from
scala.Product
.
NOTE: Pattern matching, equals and hashCode don't matter much for singletons (unless you do something really degenerate), so you're pretty much just getting serialization, a nice toString
, and some methods you probably won't ever use.