Skip to content

Commit 0cfedce

Browse files
committed
Seth's suggestions
1 parent 9f8bfd3 commit 0cfedce

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

tutorials/tour/_posts/2017-02-13-inner-classes.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,9 @@ next-page: abstract-types
1111
previous-page: lower-type-bounds
1212
---
1313

14-
In Scala it is possible to let classes have other classes as members. Opposed to Java-like languages where such inner classes are members of the enclosing class, in Scala such inner classes are bound to the outer object. To illustrate the difference, we quickly sketch the implementation of a graph datatype:
14+
In Scala it is possible to let classes have other classes as members. Opposed to Java-like languages where such inner classes are members of the enclosing class, in Scala such inner classes are bound to the outer object. Suppose we want the compiler to prevent us, at compile time, from mixing up which nodes belong to what graph. Path-dependent types provide a solution.
15+
16+
To illustrate the difference, we quickly sketch the implementation of a graph datatype:
1517

1618
```tut
1719
class Graph {
@@ -31,7 +33,7 @@ class Graph {
3133
}
3234
}
3335
```
34-
This program represents a graph as a list of nodes (`var nodes`). Each node knows which other nodes it's connected to (`connectedNodes`). The `class Node` is a _path-dependent type_ because it is nested in the `class Graph`. Therefore, everything in the `connectedNodes` must be created using the class attached to Graph.
36+
This program represents a graph as a list of nodes (`List[Node]`). Each node has a list of other nodes it's connected to (`connectedNodes`). The `class Node` is a _path-dependent type_ because it is nested in the `class Graph`. Therefore, all noes in the `connectedNodes` must be created using the `newNode` from the same instance of `Graph`.
3537

3638
```tut
3739
val graph1: Graph = new Graph
@@ -41,7 +43,7 @@ val node3: graph1.Node = graph1.newNode
4143
node1.connectTo(node2)
4244
node3.connectTo(node1)
4345
```
44-
Notice how the type of all of the nodes is `graph1.Node`. This is because when we call `graph1.newNode` which calls `new Node`, the method is using the instance of `Node` specific to the instance `graph1`.
46+
We have explicitly declared the type of `node1`, `node2`, and `node3` as `graph1.Node` for clarity but the compiler could have inferred it. This is because when we call `graph1.newNode` which calls `new Node`, the method is using the instance of `Node` specific to the instance `graph1`.
4547

4648
If we now have two graphs, the type system of Scala does not allow us to mix nodes defined within one graph with the nodes of another graph, since the nodes of the other graph have a different type.
4749
Here is an illegal program:

0 commit comments

Comments
 (0)