用于记录在学习 scala cookbook过程中对于新知识或者不容易记忆的内容。结构与书的章节结构相同。
Companion Objects and Create Object Instances
主要涉及6.6 6.8 6.9小节
scala does not have a static keyword, so if you want to create a class that has static methods, you can use companion objects.Like this: Define nonstatic (instance) members in your class, and define members that you want to appear as “static” members in an object that has the same name as the class, and is in the same file as the class.
1 |
|
Inorder to don’t use the new keyword to create a new instance of a class, there are two ways:
• Create a companion object for your class, and define an apply method in the companion
object with the desired constructor signature.
• Define your class as a case class
1 |
//companion object |
note:
(1) apply method is a syntactic sugar, “val p = Person(“hi”)” == “val p = Person.apply(“hi”)”
(2) with case classes, the case class generates an apply method in a companion object default.
(3) you can provid multiple apply methods in companion object match multiple constructors in class
Factory Method
you can implement the factory method with apply For instance, suppose you want to create an Animal factory that returns instances of Cat and Dog classes, based on what you ask for. By writing an apply method in the companion object of an Animal class, users of your factory can create new Cat and Dog instances like this:
1 |
val cat = Animal("cat") // creates a Cat |
To implement this behavior, create a parent Animal trait:
1 |
trait Animal { |
In the same file, create (a) a companion object, (b) the classes that extend the base trait, and (c) a suitable apply method:
1 |
object Animal { |
近期评论