[Scala] Scala基础知识

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Scala] Scala基础知识相关的知识,希望对你有一定的参考价值。

Object 

  1. 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. 
  2. Objects provide similar "static" and "global" functionality but decouple them from instantiable classes. 
  3. 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

  1. 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. 
  2. A companion object differs from other objects as it has access rights to the class/trait that other objects do not.
  3. A companion object is as a factory for creating instances of the class. 
  4. 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.
  5. 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:

  1. pattern matching support 支持模式匹配
  2. default implementations of equals and hashCode 默认实现equals和hashCode
  3. default implementations of serialization 默认实现序列化
  4. a prettier default implementation of toString, and 默认更好实现toString
  5. 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.

 

以上是关于[Scala] Scala基础知识的主要内容,如果未能解决你的问题,请参考以下文章

Beginning Scala study note Scala Type System

Beginning Scala study note Functional Programming in Scala

Beginning Scala study note Scala and Java Interoperability

Scala note 1

Spark零基础入门:Scala类型参数

Beginning Scala study note Trait