Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method from a generic constraint Dart

Tags:

generics

dart

I'm trying to call a static method from a generic type I receive. Is that even possible?

Furthermore, I apply a Type constraint in order to only manipulate the object from its parent class.

Here is a short example of what I'm trying to achieve:

class A {
  static func() {
    print("A");
  }
}

class B extends A {
  static func() {
    print("B");
  }
}

concret<T extends A>() {
  T.func(); // I expected a print('B')
}

main() {
    concret<B>();
}
like image 858
TheBichour Avatar asked May 14 '19 17:05

TheBichour


1 Answers

No, it's not possible.

Dart static method invocations are resolved at compile-time, so it's not possible to call them on type variables which only have a value at run-time.

If it was possible, it would be completely unsafe. Anyone can create a class C extending A which does not have a static func member and invoke concret<C>();. Since static members are not inherited, it would have to give you a run-time error, and there is nothing you can do to detect that at compile-time. That is the primary reason why it is not allowed.

like image 188
lrn Avatar answered Sep 18 '22 14:09

lrn