Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it possible to design a type-safe linked list preventing getNext() at the tail node?
    primarykey
    data
    text
    <p>I'm wondering if it is possible to design, for example, a type-safe singly linked list structure such that it is impossible to ask for the next node from the tail node. </p> <p>At the same time, the client would need to be able to traverse (recursively or otherwise) through the list via <code>node.getChild()</code> but be prevented at compile time (at least with human-written explicit type checking) from going past the tail. </p> <p>I'm wondering:</p> <ol> <li>Is there a name for this type of problem?</li> <li>Is there an object oriented or other approach that would help to avoid explicit run-time type checking? </li> </ol> <p>The implementation language isn't important, but here's a Java example of what I'm thinking of. </p> <p><strong>Edit after Joop's answer:</strong></p> <pre><code>public class TestHiddenInterfaces { interface Node { HasNoChildNode getTail(); } interface HasNoChildNode extends Node {}; interface HasChildNode extends Node { Node getChild(); } class HasNoChild implements HasNoChildNode { @Override public HasNoChildNode getTail() { return this; } } class HasChild implements HasChildNode { final Node child; @Override public Node getChild() { return child; } HasChild(Node child) { this.child = child; } @Override public HasNoChildNode getTail() { if(child instanceof HasChild) return ((HasChild) child).getTail(); else if(child instanceof HasNoChild) return (HasNoChildNode) child; else throw new RuntimeException("Unknown type"); } } @Test public void test() { HasNoChild tail = new HasNoChild(); assertEquals(tail, tail.getTail()); HasChild level1 = new HasChild(tail); assertEquals(tail, level1.getTail()); HasChild level2 = new HasChild(level1); assertEquals(tail, level2.getTail()); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload