Skip to content

Commit c53cf2f

Browse files
travissarlessom-snytt
authored andcommitted
rewrote singleton objects tour
1 parent e45cd10 commit c53cf2f

File tree

1 file changed

+59
-35
lines changed

1 file changed

+59
-35
lines changed

_tour/singleton-objects.md

Lines changed: 59 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -10,67 +10,91 @@ num: 13
1010

1111
next-page: regular-expression-patterns
1212
previous-page: pattern-matching
13-
1413
redirect_from: "/tutorials/tour/singleton-objects.html"
14+
prerequisite-knowledge: classes, methods, private-methods, packages, option
1515
---
1616

17-
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`.
17+
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.
1818

19+
# Defining a singleton object
20+
The simplest form of an object is the keyword `object` and an identifier:
21+
```tut
22+
object Box
1923
```
20-
package test
2124

22-
object Blah {
23-
def sum(l: List[Int]): Int = l.sum
24-
}
25+
Here's an example of an object with a method:
2526
```
27+
package logging
2628
27-
This `sum` method is available globally, and can be referred to, or imported, as `test.Blah.sum`.
28-
29-
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.
30-
31-
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.
29+
object Logger {
30+
def info(message: String): Unit = println(s"INFO: $message")
31+
}
32+
```
33+
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:
3234

33-
## Companions ##
35+
```
36+
import logging.Logger.info
3437
35-
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.
38+
class Project(name: String, daysToComplete: Int)
3639
37-
[Scaladoc]({{ site.baseurl }}/style/scaladoc.html) 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.
40+
val project1 = new Project("TPS Reports", 1)
41+
val project2 = new Project("Website redesign", 5)
42+
info("Created projects") // Prints "INFO: Created projects"
43+
```
3844

39-
A class and its companion object, if any, must be defined in the same source file. Like this:
45+
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.
4046

41-
```tut
42-
class IntPair(val x: Int, val y: Int)
47+
Note: If an `object` is nested within another construct such as a class, it is only a singleton in that context. This means there could be an `object NutritionInfo` in the `class Milk` and in the `class OrangeJuice`.
4348

44-
object IntPair {
45-
import math.Ordering
49+
## Companion objects
4650

47-
implicit def ipord: Ordering[IntPair] =
48-
Ordering.by(ip => (ip.x, ip.y))
49-
}
51+
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.
5052
```
53+
import scala.math._
5154
52-
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.
53-
54-
## Notes for Java programmers ##
55+
class Circle(val radius: Double) {
56+
def area: Double = Circle.calculateArea(radius)
57+
}
5558
56-
`static` is not a keyword in Scala. Instead, all members that would be static, including classes, should go in a singleton object. They can be referred to with the same syntax, imported piecemeal or as a group, and so on.
59+
object Circle {
60+
def calculateArea(radius: Double): Double = Pi * pow(radius, 2.0)
61+
}
5762
58-
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:
63+
val circle1 = new Circle(5.0)
5964
65+
circle1.area
6066
```
61-
class X {
62-
import X._
6367

64-
def blah = foo
68+
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.
69+
70+
The companion object can also contain factory methods:
71+
```tut
72+
class Email(val username: String, val domainName: String)
73+
74+
object Email {
75+
def fromString(emailString: String): Option[Email] = {
76+
emailString.split('@') match {
77+
case Array(a, b) => Some(new Email(a, b))
78+
case _ => None
79+
}
80+
}
6581
}
6682
67-
object X {
68-
private def foo = 42
83+
val scalaCenterEmail = Email.fromString("[email protected]")
84+
scalaCenterEmail match {
85+
case Some(email) => println(
86+
s"""Registered an email
87+
|Username: ${email.username}
88+
|Domain name: ${email.domainName}
89+
""")
90+
case None => println("Error: could not parse email")
6991
}
7092
```
93+
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.
7194

72-
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]`.
95+
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.
7396

74-
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`.
97+
## Notes for Java programmers ##
7598

76-
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.
99+
`static` is not a keyword in Scala. Instead, all members that would be static, including classes, should go in a singleton object instead.
100+
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

Comments
 (0)