Skip to content

Dynamic variable values can utilize extension functionality. #4225

Open
@Stitch-Taotao

Description

Dynamic variable values can utilize extension functionality.

It is mainly used to act like Kotlin's let extension function, making it convenient to check whether a dynamic value is null or to check its type.

extension MExt<T> on T {
  void let(void Function(T it) block) {
    if (this != null) {
      block(this);
    }
  }

  void letType<R>(void Function(R it) block) {
    if (this is R) {
      block(this as R);
    }
  }
}
void main(){
  dynamic j = 100;
  j.let((it) {
    print("print j");
  });
  j.letType<int>((it){
    print("j is int");
  });
}

The biggest problem now is that it works perfectly fine when running variables of other types, but a NoSuchMethodError will be reported when running the values of dynamic variables.

You can see more in :Dartpad demo

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions