Home > Back-end >  Elegant way to execute code on function exit in Dart
Elegant way to execute code on function exit in Dart

Time:08-13

Suppose we need to execute some code when a function finishes, no matter how. Example:

void myFunc() async {
    await myLock.acquire();
    if(...) {
        myLock.release();
        return;
    }
    ...
    myLock.release();
}

Many languages have features that allow to achieve this in a more elegant way than just manually calling myLock.release() before every return statement (For example defer in Go). Is something like that also possible in Dart?

CodePudding user response:

Dart does not have RAII. You instead would need to use try-finally.

(Dart did recently (in 2.17) add Finalizers, but those would fire when objects are garbage collected, which might happen at some non-deterministic time, if ever.)

CodePudding user response:

And just for the record, an example of using try/finally:

void myFunc() async {
  await myLock.acquire();
  try {
    if(...) {
        return;
    }  
    ...
  } finally {
    myLock.release();
  }
 
}

You'd want to start the try after allocating the resource, so that you don't try to release if allocation throws.

  •  Tags:  
  • dart
  • Related