corgrath
corgrath

Reputation: 12275

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?

Upvotes: 3

Views: 3448

Answers (5)

Larry Landry
Larry Landry

Reputation: 1311

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

Upvotes: 0

Damon
Damon

Reputation: 841

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."
}

Upvotes: 0

Hendrik Jan
Hendrik Jan

Reputation: 4908

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");

Upvotes: 1

Eduardo Copat
Eduardo Copat

Reputation: 5151

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);          
   }
}

Upvotes: 1

MarioP
MarioP

Reputation: 3832

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
}

Upvotes: 6

Related Questions