Accessing static members of a type casted to dynamic

38 views
Skip to first unread message

Ryan Gonzalez

unread,
Jun 18, 2018, 2:45:54 PM6/18/18
to misc
TL;DR: try running this in DartPad:

class X {
  static String x = 'this is X.x';
}

void main() {
  print(X.x);
  print((X as dynamic).x);
}

It will give:

this is X.x
Uncaught exception:
C.Type_X_P98.get$x is not a function

Is this a bug or known issue? Is there any way to work around it for the time being?

In my scenario, I'm passing a type like the above to a function, and I need to access a static property on it (the reasons are a bit complicated, but it basically has to do with adding a static property in a builder). Right now, I'm trying something like this:

void func(dynamic type) {
  print(type.x);
}

func(X);

but it's not working, of course...

--
Ryan (ライアン)
Yoko Shimomura, ryo (supercell/EGOIST), Hiroyuki Sawano >> everyone else
https://refi64.com/

Matan Lurey

unread,
Jun 18, 2018, 3:17:16 PM6/18/18
to mi...@dartlang.org
On Mon, Jun 18, 2018 at 11:45 AM Ryan Gonzalez <rym...@gmail.com> wrote:
TL;DR: try running this in DartPad:

class X {
  static String x = 'this is X.x';
}

void main() {
  print(X.x);
  print((X as dynamic).x);
}

It will give:

this is X.x
Uncaught exception:
C.Type_X_P98.get$x is not a function

Is this a bug or known issue? Is there any way to work around it for the time being?

No, the Dart language does not have dynamic access to static members (static members are not part of the interface of a class - they are basically just sugar instead of using top-level methods or fields).
 
In my scenario, I'm passing a type like the above to a function, and I need to access a static property on it (the reasons are a bit complicated, but it basically has to do with adding a static property in a builder). Right now, I'm trying something like this:

void func(dynamic type) {
  print(type.x);
}

func(X);

but it's not working, of course...

You'll need to restructure how you are writing your types. A popular way is having two types:

class Builder<T> {
  T build();
}

class X {
  String x = 'This is X';
}

class XBuilder implements Builder<X> {
  @override
   T build() => new X();
}
 

--
Ryan (ライアン)
Yoko Shimomura, ryo (supercell/EGOIST), Hiroyuki Sawano >> everyone else
https://refi64.com/

--
For more ways to connect visit https://www.dartlang.org/community
---
You received this message because you are subscribed to the Google Groups "Dart Misc" group.
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/CAO41-mMGmoB70MiUMs0p041z6G1YWuy2rXX8D4k6MZojcFrbmw%40mail.gmail.com.
Reply all
Reply to author
Forward
0 new messages