1

in my program, I wish to different behavior depending on whether a class has been defined.

if one had undefined as in javascript, something like this:

  var i = (NewClass == undefined) ? new OldClass() : new NewClass();

since Dart is compiled, can something like this be done?


seems the best answer is to search for the class NewClass using the string "NewClass". see Instantiate a class from a string

Community
  • 1
  • 1
cc young
  • 15,035
  • 25
  • 76
  • 138
  • Actually, that code wouldn't work in JavaScript, either, you'd get a `ReferenceError` if `NewClass` hadn't been declared at all. `(typeof NewClass === "undefined")` would work, perhaps there's a Dart equivalent. – T.J. Crowder Jan 22 '14 at 06:50

1 Answers1

2

I'm not sure what you actually want to express.

In Dart you can't dynamically define classes (at least not yet)
therefore such an if makes no sense.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • a library may or may not have been included, which would have added `NewClass` – cc young Jan 22 '14 at 07:17
  • It makes no sense to check this at runtime. You can only add it at compile time. You could also write `if (I have not written correct code) { do the right thing anyways; }` – Günter Zöchbauer Jan 22 '14 at 07:20
  • Dart has no concept of dynamic-loading? Really? – T.J. Crowder Jan 22 '14 at 07:21
  • No, at least not yet. There are plans but not more. – Günter Zöchbauer Jan 22 '14 at 07:21
  • @GünterZöchbauer: Huh, that's really surprising. But a quick search suggests that the closest you can come is [isolates](https://api.dartlang.org/docs/channels/stable/latest/dart_isolate.html), which are a lot like web workers, and not related to the situation in the OP's question. +1 – T.J. Crowder Jan 22 '14 at 07:23
  • 1
    Yes but isolates load only compiled units as well. You can only communicate using serialized objects (byte sequences). If the type is not included in the receiving isolate's code, it can't deserialize to the origin type. – Günter Zöchbauer Jan 22 '14 at 07:25
  • is it possible to search for a class by it's name? if so, could solve problem that way. – cc young Jan 22 '14 at 07:26
  • Yes that can be done. AFAIK there are already answered questions about this on SO. If not it's probably better to start a new one. – Günter Zöchbauer Jan 22 '14 at 07:27
  • 1
    indeed - http://stackoverflow.com/questions/14242712/instantiate-a-class-from-a-string – cc young Jan 22 '14 at 07:58