The accessor throws an exception and with the semantics you propose it will happily be wrapped by as many MatchExceptions as possible.

But this class is already so deeply questionable, because accessors should not throw exceptions, that we've lost the game before we started.  Whether the exception comes wrapped or not is like asking "do you want whipped cream on your mud and axle-grease pie" :)

(Also, I don't see where the exception is wrapped multiple times? So I'm not even sure you are clear on what is being propsed.)



public sealed interface RecChain {
  default int size() {
    return switch (this) {
      case Nil __ -> 0;
      case Cons(var v, var s, var next) -> 1 + next.size();
    };
  }

  record Nil() implements RecChain { }

  record Cons(int value, int size, RecChain next) implements RecChain {
    @Override
    public int size() {
      return size != -1? size: RecChain.super.size();
    }
  }

  public static void main(String[] args){
    RecChain chain = new Nil();
    for (var i = 0; i < 100; i++) {
      chain = new Cons(i, -1, chain);
    }
    System.out.println(chain.size());
  }
}


Rémi

Reply via email to