Does the Dart programming language have an equivalent to Javascript's "prototype"? - dart

In Dart, is it possible for a function to have a prototype associated with it?
Example Javascript code:
doStuff.prototype.isDefined = true; //is there anything like Javascript's function prototypes in Dart?
function doStuff(){
console.log("The function doStuff was called!");
}
Is it possible to do the equivalent of this in Dart (i.e., create a list of properties for each function?)

Two things to address here:
First, Dart doesn't have prototypes or prototypal inheritance, and instead uses classical inheritance. Rather than a prototype, objects have a class, and instead of a prototype chain, objects have superclasses.
Second, for your specific case, I think we'd have to see more of what you need to do to figure out the idiomatic way to do it in Dart. It should soon be possible to emulate functions with objects so that you can invoke an object and still have state and other methods associated with it.
See this article for more: http://www.dartlang.org/articles/emulating-functions/
When that capability lands you'll be able to do this:
class DoStuff {
bool isDefined = true;
call() => print("The function doStuff was called!");
}
var doStuff = new DoStuff();
main() => doStuff();
Which works if you have a fixed set of metadata about your function that you need to keep track of. It's slightly different from JavaScript because each instance of the function in Dart will have its own state for isDefined. I'm not sure if it's possible or easy to get multiple instances of the function in JavasScript, but you might need to make isDefined static so that the value is shared across all instances.

Dart does not allow you to add or remove member variables from an instance of a class at runtime. Rewriting your example in Dart it might look something like this:
class doStuff {
bool isDefined;
doStuff() {
isDefined = true;
}
void stuff() {
print('The function stuff was called!');
}
}
main() {
new doStuff().stuff();
}
If you wanted to add a property bag to a class in Dart you would write:
class PropertyObject {
Map<String, Dynamic> properties;
PropertyObject() {
properties = new Map<String, Dynamic>();
}
Dynamic operator[](String K) => properties[K];
void operator[]=(String K, Dynamic V) => properties[K] = V;
}
main() {
PropertyObject bag = new PropertyObject();
bag['foo'] = 'world';
print('Hello ${bag['foo']}');
}
Note that you can't access map properties using the '.' operator.

Related

Provide function context in dart

So i need to run some code that needs to get some data later.
I imagine it like:
voin runWithContext(void Function () fn, dynamic context) {
// ... magic
fn();
}
And later in the call stack of fn()
void otherFn() {
dynamic context = getContext();
}
If functions are not async we could just store the context as global variable, but the main requirement to support dart:async
I was looking into dart:mirrors and stacktrace but i can't find no way to bind some data.
You can do this with Zones.
Zones, and their "zone variables" are the canonical way to create a context that is preserved throughout an asynchronous computation).
Since you want single global function to access the context, it will have to be untyped (or typed at the one type that you need, but not generally reusable). That would me me want to reconsider the design, but if it works for you, I'd do it as:
import "dart:async";
/// Container for a mutable value.
class _Context {
dynamic value;
}
final _Context _rootContext = _Context();
R runWithNewContext<R>(R Function() body) =>
runZoned(body, zoneValues: {
#_context: _Context()..value = context,
});
dynamic get context => (Zone.current[#_context] ?? _rootContext).value;
set context(dynamic value) {
(Zone.current[#_context] ?? _rootContext).value = value;
}
If you don't need the mutability, you can simplify things a little, but not much.
The typed and unmodifable alternative is something like
class _Box { // Distinguishable from `null`, even if value is `null`
final Object? value;
_Box(this.value);
}
class ZoneStorage<T> {
final _Box _initialValue;
ZoneStorage(T initialValue) : _initialValue = _Box(initialValue);
R update<R>(T newValue, R Function() body) =>
runZoned(body, zoneValues: {this: _Box(newValue)});
T get value =>
(Zone.current[this] as _Box? ?? _initialValue).value as T;
}
That allows you to create multiple independent zone stores, like:
var zs1 = ZoneStorage<int>(1);
var zs2 = ZoneStorage<String>("yup");
zs1.update(42, () {
print(zs1.value);
print(zs2.value);
});
zs2.update("yup yup yup", () {
print(zs1.value);
print(zs2.value);
});
So the thing that is need is https://api.dart.dev/stable/2.17.3/dart-async/Zone-class.html
Hope that answer will help someone else

How can I extend functions in Dart?

I know about the extension feature in Dart, but how can I use it with functions?
Essentially, I am facing two problems:
What do I extend on (extension FancyFunction on ?)?
I would want to add a function like toAsync that makes the function return a Future of its usual result.
How would I implement calling?
I could create a callAsync member that executes this() or this.call(), but I would like to use regular calling syntax, i.e. just parentheses.
What do I extend on when extending functions?
Dart has a Function type. This can be extended on and you can pass type parameters if you want.
Here is an example from the changelog:
extension CurryFunction<R, S, T> on R Function(S, T) { ... }
Furthermore, you can extend any typedef of a function.
For adding the toAsync and callAsync functionality a generic return type R will do. Note that this will only extend functions without parameters as Function() takes no parameters:
extension FancyFunction<R> on R Function() {
Future<R> Function() toAsync() => () async => this();
}
Now, this could be used like this:
void syncHello() => print('Hello');
void main() {
final asyncHello = syncHello.toAsync();
asyncHello().then((_) => print(', World!'));
}
How do I implement calling?
Every class in Dart can implement the call method. You can either execute this method simply using parentheses or with .call().
Here is an example implementation:
extension FancyFunction<R> on R Function() {
Future<R> call() async => this();
}
Since every Function already implements call, the extension member cannot be called implicitly.
Instead, you will have to explicitly declare your function as a FancyFunction to be able to call it:
void syncHello() => print('Hello');
void main() {
FancyFunction(syncHello)()
.then((_) => print(', World!'));
}
Note that FancyFunction(syncHello)() is the same method call as FancyFunction(syncHello).call().
However, now we have two problems:
We have to explicitly declare our function to be a FancyFunction, which somewhat defeats the purpose of having an extension.
The call method will always return a Future as the regular call method cannot be accessed anymore when we declare a FancyFunction.
Instead, adding a method like callAsync seems like a better solution:
extension FancyFunction<R> on R Function() {
Future<R> callAsync() async => this();
}
Now, callAsync can be used implicitly again:
void syncHello() => print('Hello');
void main() {
syncHello.callAsync()
.then((_) => print(', World!'));
syncHello(); // regular call
}

How can I create a Dart Function from a String?

I have a List<String> of Dart function names. For example, ['func1', 'func2', 'func3']. I want to call each function in the List. How can I go from a String to a Function? The following code does not work, but conceptually it does what I want:
var func1 = Function('func1');
See how it creates a Function from 'func1'.
Edit: I need to deal with Strings because I read the list of functions from a file.
I don't think Dart allows that at the moment (for objects you could use dart:mirrors, but it's currently marked as an unstable library).
An alternative is to use a Map to associate the strings with the functions, as in:
void foo() {
print('foo');
}
void bar() {
print('bar');
}
void main() {
var functions = {
'foo': foo,
'bar': bar
};
// calling foo()
functions['foo']();
// or
var b = functions['bar'];
b();
}

Dart - named parameters using a Map

I would like to know if I can call a function with name parameters using a map e.g.
void main()
{
Map a = {'m':'done'}; // Map with EXACTLY the same keys as slave named param.
slave(a);
}
void slave({String m:'not done'}) //Here I should have some type control
{
print(m); //should print done
}
the hack here is to not use kwargs but a Map or, if you care about types, some interfaced class (just like Json-obj), but wouldn't be more elegant to just have it accept map as kwars?
More, using this hack, optional kwargs would probably become a pain...
IMHO a possible implementation, if it does not exist yet, would be something like:
slave(kwargs = a)
e.g. Every function that accepts named param could silently accept a (Map) kwargs (or some other name) argument, if defined dart should, under the hood, take care of this logic: if the key in the Map are exactly the non optional ones, plus some of the optional ones, defined in the {} brackets, and of compatible types "go on".
You can use Function.apply to do something similar :
main() {
final a = new Map<Symbol, dynamic>();
a[const Symbol('m')] = 'done';
Function.apply(slave, [], a);
}
You can also extract an helper method to simplify the code :
main() {
final a = symbolizeKeys({'m':'done'});
Function.apply(slave, [], a);
}
Map<Symbol, dynamic> symbolizeKeys(Map<String, dynamic> map){
return map.map((k, v) => MapEntry(Symbol(k), v));
}
The answer of #alexandre-ardhuin is correct but is missing something : How to call a constructor as Function.
You have to use the property new after the Classname. Here's an example :
main() {
final a = new Map<Symbol, dynamic>();
Function.apply(MyClass.new, [], a);
}

Loading classes dynamically in Dart

So, I looked into mirror and they might be an option, but given their async nature they might be really awkward to use or just not viable in the long run. Since they are currently not supported (just a play-thing) they are not really viable at this time anyway.
Question: Given a series of Strings, eg. [ "Foo", "Bar" ] a base class Application and Widget in library corelib; and a corresponding class for each of the strings FooWidget, BarWidget in library applibrary;, what's currently the most elegant method to get Application to turn the strings into instances of the corresponding classes, that works with dart2js.
Equivalent PHP pseudo-example for clarity,
<?php # example
namespace corelib;
class Widget {
function name() {
return \get_called_class();
}
}
class Application {
static function resolve($name, $library) {
$class = $library.'\\'.$name.'Widget';
return new $class;
}
}
namespace applibrary;
class FooWidget extends \corelib\Widget {
// ...
}
class BarWidget extends \corelib\Widget {
// ...
}
$foowidget = \corelib\Application::resolve('Foo', 'applibrary');
$barwidget = \corelib\Application::resolve('Bar', 'applibrary');
echo "{$foowidget->name()} <br> {$barwidget->name()}";
Output
applibrary\FooWidget
applibrary\BarWidget
If you can validate the list of strings, then the best way for the moment (until mirror support in dart2js becomes better baked), is likely an if statement.
// toy implementation
Widget getWidget(name) {
switch (name) {
case "Foo": return new FooWidget();
case "Bar": return new FooWidget();
default: // handle error
}
}
// elsewhere:
var fooWidget = getWidget("Foo");
var barWidget = getWidget("Bar");
The list of xyzWidget classes will be a finite list (as you can't dynamically link in code at runtime anyway).
Of course, a more elegant implementation is to use mirrors (shown below, for reference, although it doesn't currently fulfil the dar2js criteria)
Future<Widget> getWidget(library, name) {
var completer = new Completer<Widget>();
MirrorSystem ms = currentMirrorSystem();
ClassMirror cm = ms.libraries[library].classes[name];
// instantiate an instance of the class
cm.newInstance(null,[]).then((instance) => completer.complete(instance));
return completer.future;
}
// elsewhere:
getWidget("applibrary","FooWidget").then((Widget widget) {
// do something with widget
});

Resources