How can an `extension` reference the type of `this` in dart?

29 Views Asked by At

Let's say I have some datatypes, and I want a function gimmeThis() that simply returns this. Currently, the code in main() does not compile, because the result of gimmeThis() is MyClass. How can I change the extension class to return a more specific type when gimmeThis() is called?

class MyClass {}
class MySubclass1 extends MyClass {}
class MySubclass2 extends MyClass {}

extension MyClassOperations on MyClass {
  // how to replace `MyClass` with the actual type of `this`?
  MyClass gimmeThis() => this;
}

void main() {
  MySubclass1 sub1 = MySubclass1().gimmeThis();
  MySubclass2 sub2 = MySubclass2().gimmeThis();
}
1

There are 1 best solutions below

0
Taylor Brown On

Just did a little more digging, and I actually found this post that gives insight to the answer I was looking for!

extension MyClassOperations<MyClassT extends MyClass> on MyClassT {
  MyClassT gimmeThis() => this;
}

What?! Extending a generic type?!! Dart is such a cool language, I keep learning about new ways to use it that just makes programming in it so much fun!