Eager static variable initialization.

31 views
Skip to first unread message

Henry David Spells III

unread,
Dec 17, 2021, 1:45:51 PM12/17/21
to Dart Misc
I realize that lazy initialization of static variables is a great feature. However, there are some cases where I want eager evaluation without having to specifically reference the variable in any location. Take the following class for instance.

typedef JSONCreator<T> = T Function(Map<String, dynamic>);

class JSONModelFactory<T extends JSONModel> {
  static final Map<Type, JSONCreator> _jsonModelFactoryMap = <Type, JSONCreator>{};

  JSONModelFactory(JSONCreator<T> creator) {
    _jsonModelFactoryMap[T] = creator;
  }
  static T? create<T>(Map<String, dynamic> data) {
    JSONCreator? creator = _jsonModelFactoryMap[T];
    if (creator != null) {
      return creator(data);
    }
    return null;
  }
}

and it's corresponding simplified use case.

class AcknowledgeRequest extends JSONModel {
  static JSONModelFactory<AcknowledgeRequest> factory = JSONModelFactory(AcknowledgeRequest.create);

  AcknowledgeRequest.base(Map<String, dynamic> jsonData)
      : super(jsonData);

  AcknowledgeRequest(Map<String, dynamic> jsonData) : this.base(JSONModel.caseInsensitiveMap(jsonData));

  static AcknowledgeRequest create(Map<String, dynamic> jsonData) {
    return AcknowledgeRequest(jsonData);
  }
}

I would like each class to be able to register its factory method without have any one class/file to know about the others.

I want to be able to call

JSONModelFactory.create<T>(...) of course.

Ideally I would be able annotate the variable as @eager or something like that.

Is there anyway to do this? Preferably an easy way.
Reply all
Reply to author
Forward
0 new messages