Skip to content

Tour: "Singleton Objects" #312

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 14, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion tutorials/tour/case-classes.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ will print
Var(x) == Var(x) => true
Var(x) == Var(y) => false

It makes only sense to define case classes if pattern matching is used to decompose data structures. The following object defines a pretty printer function for our lambda calculus representation:
It makes only sense to define case classes if pattern matching is used to decompose data structures. The following [object](singleton-objects.html) defines a pretty printer function for our lambda calculus representation:

object TermTest extends scala.App {
def printTerm(term: Term) {
Expand Down
2 changes: 1 addition & 1 deletion tutorials/tour/extractor-objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ tutorial: scala-tour
num: 8
---

In Scala, patterns can be defined independently of case classes. To this end, a method named unapply is defined to yield a so-called extractor. For instance, the following code defines an extractor object Twice.
In Scala, patterns can be defined independently of case classes. To this end, a method named unapply is defined to yield a so-called extractor. For instance, the following code defines an extractor [object](singleton-objects.html) Twice.

object Twice {
def apply(x: Int): Int = x * 2
Expand Down
64 changes: 64 additions & 0 deletions tutorials/tour/singleton-objects.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
layout: tutorial
title: Singleton Objects

disqus: true

tutorial: scala-tour
num: 28
---

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`.

package test

object Blah {
def sum(l: List[Int]): Int = l.sum
}

This `sum` method is available globally, and can be referred to, or imported, as `test.Blah.sum`.

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.

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.

## Companions ##

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. This is so common that it's safe to refer to singleton objects as “companion objects” informally, without much risk of confusion.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't agree with this last sentence; it seems incorrect and misleading to me to call something a "companion object" unless it actually is one. Let's not encourage this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@SethTisue I agree.


[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.

A class and its companion object, if any, must be defined in the same source file. Like this:

class IntPair(val x: Int, val y: Int)

object IntPair {
import math.Ordering

implicit def ipord: Ordering[IntPair] =
Ordering.by(ip => (ip.x, ip.y))
}

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.

## Notes for Java programmers ##

`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.

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:

class X {
import X._

def blah = foo
}

object X {
private def foo = 42
}

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]`.

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`.

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.
2 changes: 1 addition & 1 deletion tutorials/tour/tour-of-scala.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Scala is a modern multi-paradigm programming language designed to express common
Scala is a pure object-oriented language in the sense that [every value is an object](unified-types.html). Types and behavior of objects are described by [classes](classes.html) and [traits](traits.html). Classes are extended by subclassing and a flexible [mixin-based composition](mixin-class-composition.html) mechanism as a clean replacement for multiple inheritance.

## Scala is functional ##
Scala is also a functional language in the sense that [every function is a value](unified-types.html). Scala provides a [lightweight syntax](anonymous-function-syntax.html) for defining anonymous functions, it supports [higher-order functions](higher-order-functions.html), it allows functions to be [nested](nested-functions.html), and supports [currying](currying.html). Scala's [case classes](case-classes.html) and its built-in support for [pattern matching](pattern-matching.html) model algebraic types used in many functional programming languages.
Scala is also a functional language in the sense that [every function is a value](unified-types.html). Scala provides a [lightweight syntax](anonymous-function-syntax.html) for defining anonymous functions, it supports [higher-order functions](higher-order-functions.html), it allows functions to be [nested](nested-functions.html), and supports [currying](currying.html). Scala's [case classes](case-classes.html) and its built-in support for [pattern matching](pattern-matching.html) model algebraic types used in many functional programming languages. [Singleton objects](singleton-objects.html) provide a convenient way to group functions that aren't members of a class.

Furthermore, Scala's notion of pattern matching naturally extends to the [processing of XML data](xml-processing.html) with the help of [right-ignoring sequence patterns](regular-expression-patterns.html). In this context, [sequence comprehensions](sequence-comprehensions.html) are useful for formulating queries. These features make Scala ideal for developing applications like web services.

Expand Down
2 changes: 1 addition & 1 deletion tutorials/tour/unified-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Here is an example that demonstrates that both numbers, characters, boolean valu
}
}

The program declares an application `UnifiedTypes` in form of a top-level singleton object extending `App`. The application defines a local variable `set` which refers to an instance of class `LinkedHashSet[Any]`. The program adds various elements to this set. The elements have to conform to the declared set element type `Any`. In the end, string representations of all elements are printed out.
The program declares an application `UnifiedTypes` in form of a top-level [singleton object](singleton-objects.html) extending `App`. The application defines a local variable `set` which refers to an instance of class `LinkedHashSet[Any]`. The program adds various elements to this set. The elements have to conform to the declared set element type `Any`. In the end, string representations of all elements are printed out.

Here is the output of the program:

Expand Down