scala cookbook chapter 6 object

用于记录在学习 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15

class (var crustType: String) {
override def toString = "Crust type is " + crustType
}
// companion object
object {
val CRUST_TYPE_THIN = "thin"
val CRUST_TYPE_THICK = "thick"
def getFoo = "Foo"
}

//how to use
println(Pizza.CRUST_TYPE_THIN)
var p = new Pizza(Pizza.CRUST_TYPE_THICK)
println(p)

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//companion object
class Person{
var name: String = _
}
Object Persion {
def apply(name: String): Person = {
var p = new Person
p.name = name
}
}
//use
val dawn = Person("Dawn")
val a = Array(Person("Dan"), Person("Eli"))

//case class
case Person(name: String)
val john = Person("John")

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
2
val cat = Animal("cat") // creates a Cat
val dog = Animal("dog") // creates a Dog

To implement this behavior, create a parent Animal trait:

1
2
3
trait Animal {
def speak
}

In the same file, create (a) a companion object, (b) the classes that extend the base trait, and (c) a suitable apply method:

1
2
3
4
5
6
7
8
9
10
11
12
13
object Animal {
private class Dog extends Animal {
override def speak { println("woof") }
}
private class Cat extends Animal {
override def speak { println("meow") }
}
// the factory method
def apply(s: String): Animal = {
if (s == "dog") new Dog
else new Cat
}
}