Access global function

58 views
Skip to first unread message

A Matías Quezada

unread,
Feb 23, 2012, 1:25:21 PM2/23/12
to General Dart Discussion
Hi, I'm trying to create a interface Printer with a method print. One of Printer implementations is ConsolePrinter, I need it to print to the console, with the global print(string) function.

interface Printer {
  print(message);
}

class ConsolePrinter implements Printer {
  print(message) =>
    /*global*/ print(message);
}

main() {
  new ConsolePrinter().print("Hi");
}

The problem is obiously than this line 
  print(message) =>
    /*global*/ print(message);

(Warning: Execute this code will fill Javascript callstack)

Is recursive, I don't want to so...

How can I access global "print" function from a class who already has a "print" method?

---
A. Matías Quezada

Sam McCall

unread,
Feb 23, 2012, 4:17:57 PM2/23/12
to General Dart Discussion
Here's a few ways, I'm sure there are lots more:

Function consolePrint = print;
class ConsolePrinter {
print(m) => consolePrint(m);
}

consolePrint(m) => print(m);
class ConsolePrinter {
print(m) => consolePrint(m);
}

#import('dart:core', prefix:'core');
class ConsolePrinter {
print(m) => core.print(m);
}

(The last one would AFAIK the only way to do this if your print was a
top-level function)

Bob Nystrom

unread,
Feb 23, 2012, 4:22:20 PM2/23/12
to Sam McCall, General Dart Discussion
On Thu, Feb 23, 2012 at 1:17 PM, Sam McCall <samm...@google.com> wrote:
Here's a few ways, I'm sure there are lots more:

Function consolePrint = print;
class ConsolePrinter {
 print(m) => consolePrint(m);
}

consolePrint(m) => print(m);
class ConsolePrinter {
 print(m) => consolePrint(m);
}

Yeah, that's the "best" solution I can think of. It's still pretty gross.


#import('dart:core', prefix:'core');
class ConsolePrinter {
 print(m) => core.print(m);
}

This has the deeply unpleasant side-effect of requiring you to prefix everything from dart:core. Like int and List. :(

I'll use this as an opportunity to point out that only supporting global prefixes is really painful. This is something I really hope we can change at some point.

If this was me, I'd try to come up with a different name for the method than print(). Even if you can make it work, it will likely confuse readers of the code who will assume print() means the built-in function. Having a print() method in a superclass will also do confusing things because in the subclass, a bare call to print() will actually prefer the built-in function over the inherited method.

- bob

Reply all
Reply to author
Forward
0 new messages