You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Methods and values that aren't associated with individual instances of a [class](classes.html) belong in *singleton objects*, denoted by using the keyword `object` instead of `class`.
16
+
A singleton object is an instance of a new class. There is exactly one instance of each singleton object. They do not have constructors so they cannot be instantiated.
16
17
18
+
# Defining a singleton object
19
+
The simplest form of an object is the keyword `object` and an identifier:
20
+
```tut
21
+
object Box
17
22
```
18
-
package test
19
23
20
-
object Blah {
21
-
def sum(l: List[Int]): Int = l.sum
22
-
}
24
+
Here's an example of an object with a method:
23
25
```
26
+
package logging
24
27
25
-
This `sum` method is available globally, and can be referred to, or imported, as `test.Blah.sum`.
26
-
27
-
Singleton objects are sort of a shorthand for defining a single-use class, which can't directly be instantiated, and a `val` member at the point of definition of the `object`, with the same name. Indeed, like `val`s, singleton objects can be defined as members of a [trait](traits.html) or class, though this is atypical.
28
-
29
-
A singleton object can extend classes and traits. In fact, a [case class](case-classes.html) with no [type parameters](generic-classes.html) will by default create a singleton object of the same name, with a [`Function*`](http://www.scala-lang.org/api/current/scala/Function1.html) trait implemented.
30
-
31
-
## Companions ##
28
+
object Logger {
29
+
def info(message: String): Unit = println(s"INFO: $message")
30
+
}
31
+
```
32
+
The method `info` can be imported from anywhere in the program. Creating utility methods like this is a common use case for singleton objects (however, more sophisticated logging techniques exist). Let's see how to use `info` in another package:
32
33
33
-
Most singleton objects do not stand alone, but instead are associated with a class of the same name. The “singleton object of the same name” of a case class, mentioned above, is an example of this. When this happens, the singleton object is called the *companion object* of the class, and the class is called the *companion class* of the object.
34
+
```
35
+
import logging.Logger.info
34
36
35
-
[Scaladoc](https://wiki.scala-lang.org/display/SW/Introduction) has special support for jumping between a class and its companion: if the big “C” or “O” circle has its edge folded up at the bottom, you can click the circle to jump to the companion.
37
+
class Project(name: String, daysToComplete: Int)
36
38
37
-
A class and its companion object, if any, must be defined in the same source file. Like this:
39
+
val project1 = new Project("TPS Reports", 1)
40
+
val project2 = new Project("Website redesign", 5)
41
+
info("Created projects") // Prints "INFO: Created projects"
42
+
```
38
43
39
-
```tut
40
-
class IntPair(val x: Int, val y: Int)
44
+
The `info` method becomes visible in the scope of the package using `import logging.Logger.info`. You could also use `import logging.Logger._` to import everything from Logger.
41
45
42
-
object IntPair {
43
-
import math.Ordering
46
+
## Companion objects
44
47
45
-
implicit def ipord: Ordering[IntPair] =
46
-
Ordering.by(ip => (ip.x, ip.y))
47
-
}
48
+
A singleton object with the same name as a class is called a _companion object_. Conversely, the class is the object's companion class. The companion class and object can access each other's private members. Use a companion object for methods and values which are not specific to instances of the companion class.
48
49
```
50
+
import scala.math._
49
51
50
-
It's common to see typeclass instances as [implicit values](implicit-parameters.html), such as `ipord` above, defined in the companion, when following the typeclass pattern. This is because the companion's members are included in the default implicit search for related values.
51
-
52
-
## Notes for Java programmers ##
52
+
class Circle(val radius: Double) {
53
+
def area: Double = Circle.calculateArea(radius)
54
+
}
53
55
54
-
`static` is not a keyword in Scala. Instead, all members that would be static, including classes, should go in a singleton object instead. They can be referred to with the same syntax, imported piecemeal or as a group, and so on.
56
+
object Circle {
57
+
def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)
58
+
}
55
59
56
-
Frequently, Java programmers define static members, perhaps `private`, as implementation aids for their instance members. These move to the companion, too; a common pattern is to import the companion object's members in the class, like so:
60
+
val circle1 = new Circle(5.0)
57
61
62
+
circle1.area
58
63
```
59
-
class X {
60
-
import X._
61
64
62
-
def blah = foo
65
+
The `class Circle` contains the val `radius` which is specific to each instance whereas the `object Circle` contains the method `calculateArea` which is the same for every instance.
66
+
67
+
The companion object can also contain factory methods:
68
+
```tut
69
+
class Email(val username: String, val domainName: String)
case None => println("Error: could not parse email")
67
88
}
68
89
```
90
+
The `object Email` contains a factory `fromString` which creates an `Email` instance from a String. We return it as an `Option[Email]` in case of parsing errors.
69
91
70
-
This illustrates another feature: in the context of `private`, a class and its companion are friends. `object X` can access private members of `class X`, and vice versa. To make a member *really* private to one or the other, use `private[this]`.
92
+
Note: If a class or object has a companion, both must be defined in the same file. To define them in the REPL, you must enter `:paste` and then paste in the class and companion object code.
71
93
72
-
For Java convenience, methods, including `var`s and `val`s, defined directly in a singleton object also have a static method defined in the companion class, called a *static forwarder*. Other members are accessible via the `X$.MODULE$` static field for `object X`.
94
+
## Notes for Java programmers ##
73
95
74
-
If you move everything to a companion object and find that all you have left is a class you don't want to be able to instantiate, simply delete the class. Static forwarders will still be created.
96
+
`static` is not a keyword in Scala. Instead, all members that would be static, including classes, should go in a singleton object instead.
97
+
When using a companion object from Java code, the members will be defined in a companion class with a `static` modifier. This is called _static forwarding_. It occurs even if you haven't defined a companion class yourself.
0 commit comments