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
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 nodes in the `connectedNodes` must be created using the `newNode` from the same instance of `Graph`.
36
57
58
+
{% tabs inner-classes_2 %}
59
+
{% tab 'Scala 2 and 3' for=inner-classes_2 %}
37
60
```scala mdoc
38
61
valgraph1:Graph=newGraph
39
62
valnode1: graph1.Node= graph1.newNode
@@ -42,11 +65,16 @@ val node3: graph1.Node = graph1.newNode
42
65
node1.connectTo(node2)
43
66
node3.connectTo(node1)
44
67
```
68
+
{% endtab %}
69
+
{% endtabs %}
70
+
45
71
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`.
46
72
47
73
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.
48
74
Here is an illegal program:
49
75
76
+
{% tabs inner-classes_3 %}
77
+
{% tab 'Scala 2 and 3' for=inner-classes_3 %}
50
78
```scala mdoc:fail
51
79
valgraph1:Graph=newGraph
52
80
valnode1: graph1.Node= graph1.newNode
@@ -56,8 +84,13 @@ val graph2: Graph = new Graph
56
84
valnode3: graph2.Node= graph2.newNode
57
85
node1.connectTo(node3) // illegal!
58
86
```
87
+
{% endtab %}
88
+
{% endtabs %}
89
+
59
90
The type `graph1.Node` is distinct from the type `graph2.Node`. In Java, the last line in the previous example program would have been correct. For nodes of both graphs, Java would assign the same type `Graph.Node`; i.e. `Node` is prefixed with class `Graph`. In Scala such a type can be expressed as well, it is written `Graph#Node`. If we want to be able to connect nodes of different graphs, we have to change the definition of our initial graph implementation in the following way:
0 commit comments