简体   繁体   中英

Is it possible to override a top-level function in Dart?

Lets say I have this top-level function:

function log(String message) {
    print(message);
}

Is it possible to override this function in Dart?

Simple answer: No. The top-level can't be subclassed, so overriding isn't possible.

Longer answer: You can "overshadow" them, but depending on your use-case, this may not be what you want.

If you want to change the behaviour of a top-level method of a 3rd-party-library that gets called by the library itself, this isn't possible (at least, I don't know any way to do this).

If you just want to define a method with the same name for use in your own library, you can just define the method and use it. If both the library and your own method is needed in the importing dart file, you can prefix the library and call it with or without the prefix to distinguish the methods:

import "lib1.dart" as mylib;

void main() {
    log(); // log() method defined in this file
    mylib.log(); // log() method defined in lib1.dart
}

I'm not sure if you can override functions, but can't you wrap this into a class and use inheritance to override a method?

abstract class Parent{
  void log(String message){
    print("parent message");
    print(message);
  }
}

class Child extends Parent{
   void log(String message){
     print("child message");
     print(message);          
   }
}

That seems to be impossible.

Try this on try.dartlang.org:

test() => print('hallo');
test() => print('bye');

main() {
    test();
}

and see that you get a compilation error ("duplicate definition");

If we are talking about http://en.wikipedia.org/wiki/Method_overriding :

Is this right? I feel weird answering this so simply and definitely as those here I respect have answered no.

class Super {
    void log(){
        print("I am super.");
    }
}

class MoreSuper extends Super {
    void log() {
        print("I am superer.");
    }
}

void main() {
    var s = new Super();
    var ss = new MoreSuper();
    s.log();  // "I am super."
    ss.log(); // "I am superer."
}

I believe you can now do this using zoned execution.

This can be used to remap the print command within a test. All code that should redirect must be called from within the runZoned() call.

See: https://github.com/flutter/flutter/blob/master/packages/flutter/test/foundation/capture_output.dart

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM