Skip to content

Inherent extensions #3220

Open
Open
@ds84182

Description

@ds84182

When designing an API that includes usage of private fields that are exposed publicly in some form, it is generally undesirable to allow polymorphism on some members. Take the following example:

// Assume we're using some new nifty features for brevity purposes.
abstract base class Node<
  N extends Self,
  P extends Node<_, _, N>,
  C extends Node<N, _, _>
> {
  P? _parent;
  C? _firstChild;
  C? _lastChild;
  N? _previous;
  N? _next;

  Node.detached();

  void reparent(N parent) {
    // ... this implementation is VERY important
  }
}

A subtype can override reparent! That's not good, something like this should be statically dispatched.

The workaround today is to place it in a separate extension, but that doesn't play well with import '...' show Node;.

I propose that extension methods and bodies be allowed within classes:

abstract base class Node<...> {
  extension void reparent(N parent); // Like an extension on Node<...> but is always visible.
  extension on Node<Some, Specific, Types> {
    // Bodies are supported, with refinement typing. Just no extensions with names.
  }
}

For extension disambiguation, extension members require a cast: (node as Node).reparent(parent)

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions