Skip to content

Should non-virtual methods be generalized to classes? #2400

Open
@sigmundch

Description

@sigmundch

In the proposal for #2360, we talk about extension structs having statically dispatched methods. As hinted in #2352 (comment), I'd like to separately consider whether nonvirtual method dispatch should be it's own feature.

Part of my goal is to split what we mean by views/extension structs into smaller building blocks (similar to how "extension structs" are a specialization of "structs") - the notion of non-virtual dispatch and how we compose and create forwarding stubs can be managed as a separate feature, then views are mostly adding the notion of an erasable type.

As @leafpetersen, this exists in other languages like C#.

Some examples for illustration:

class A1 {
  int m1() => 1;
  nonvirtual int m2() => 2;
}

We could consider extends also exposing nonvirtual methods (just like extension methods do):

class A2 extends A1 {
   // inherits both m1 and m2, but m2 is dispatched statically
}

And we could consider allowing overrides or not:

class A2 extends A1 {
   nonvirtual int m2() => 3; // TBD if we allow it
}

// If we do, nonvirtual methods are dispatched statically:
// (A2() as A1).m2() returns 2

As @leafpetersen pointed out, there are special considerations to be made to handle generics:

class A<T> {
  nonvirtual void show() { print(T); };
}

void main() {
  A<num> a = A<int>();
  a.show(); // prints "num" not "int"?
}

cc @leafpetersen @mit-mit @lrhn @eernstg @chloestefantsova @johnniwinther @munificent @stereotype441 @natebosch @jakemac53 @rakudrama @srujzs @rileyporter @mraleph

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