Calling a static method from a generic constraint Dart

孤者浪人 提交于 2020-08-25 04:59:39

问题


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>();
}

回答1:


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.



来源:https://stackoverflow.com/questions/56135525/calling-a-static-method-from-a-generic-constraint-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!