I am trying to get callable classes to work in dart, but I have ran into a few issues. First thing I realized is that a normal function
myFunc() {
return 'myFunc';
}
Function.apply(myFunc,null);
is not working as a callable.
Then I realized that if I do
final myFunc = () => 'myFunc';
Function.apply(myFunc,null);
this works.
So now I am trying it out with classes
class Cars {
call(Map<Symbol,dynamic> args) {
return "ride";
}
const Cars();
}
final cars = Cars();
final jobs = {cars.hashCode :cars};
void main() {
int code = cars.hashCode;
print(Function.apply(jobs[code],null));
}
but in DartPad I get the following error
Uncaught exception:
NoSuchMethodError: method not found: 'call'
Receiver: Closure 'call$1' of Instance of 'Cars'
Arguments: []
are there some restrictions on the call method? Or how it works with Function.apply() that I am not finding in the docs?
Thanks.
Your first example works fine for me, but your program needs an entry point:
myFunc() {
return 'myFunc';
}
void main() {
print(Function.apply(myFunc, null));
}
In your class example, your call method requires a Map, but you're passing null. There is no call method with zero arguments, hence the method not found: 'call' error.
One way to fix it is by adding an empty Map to the parameter list in Function.apply:
class Cars {
call(Map<Symbol,dynamic> args) {
return "ride";
}
const Cars();
}
final cars = Cars();
final jobs = {cars.hashCode :cars};
void main() {
int code = cars.hashCode;
print(Function.apply(jobs[code], [Map<Symbol,dynamic>()]));
}
It's worth noting that you can call any method on a class with any number of arguments:
class Car {
go(int speed, int wheels) {
print('$speed mph, $wheels wheels');
}
}
void main() {
var car = Car();
Function.apply(car.go, [50, 4]);
}
Related
I've got the following code in a console application:
import 'dart:mirrors';
void main() {
final foo = Foo();
final mirror = reflect(foo);
final instanceMirror = mirror.invoke(#test, []);
print(instanceMirror);
}
class Foo {
int get test {return 42;}
}
When I run it I get an exception:
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: Class 'int' has no instance method 'call'.
Receiver: 42
Tried calling: call())
If I set a breakpoint on test then it is hit before the exception, so it's definitely invoking the property.
Why is an exception being thrown?
UPDATE: ultimately what I am trying to achieve is to grab the values of all properties in an object. Per #mezoni's answer, it seems I need to treat properties as fields rather than methods (the opposite of C#, incidentally). However, it's still not entirely clear why or how to enumerate all fields. The best I've gotten is this:
import 'dart:mirrors';
void main() {
final foo = Foo();
final mirror = reflect(foo);
for (var k in mirror.type.instanceMembers.keys) {
final i = mirror.type.instanceMembers[k];
if (i.isGetter && i.simpleName != #hashCode && i.simpleName != #runtimeType) {
final instanceMirror = mirror.getField(i.simpleName);
print("${MirrorSystem.getName(i.simpleName)}: ${instanceMirror.reflectee}");
}
}
}
class Foo {
int get someOther {
return 42;
}
int get test {
return someOther + 13;
}
}
Please try this code:
import 'dart:mirrors';
void main() {
final foo = Foo();
final mirror = reflect(foo);
final instanceMirror = mirror.getField(#test);
print(instanceMirror.reflectee);
}
class Foo {
int get test {
return 42;
}
}
I'm essentially looking for the JavaScript arguments functionality but in Dart.
Is this possible in Dart?
You have to play with noSuchMethod to do that (see Creating function with variable number of arguments or parameters in Dart)
Either at the class level:
class A {
noSuchMethod(Invocation i) {
if (i.isMethod && i.memberName == #myMethod){
print(i.positionalArguments);
}
}
}
main() {
var a = new A();
a.myMethod(1, 2, 3); // no completion and a warning
}
Or at field level :
typedef dynamic OnCall(List l);
class VarargsFunction extends Function {
OnCall _onCall;
VarargsFunction(this._onCall);
call() => _onCall([]);
noSuchMethod(Invocation invocation) {
final arguments = invocation.positionalArguments;
return _onCall(arguments);
}
}
class A {
final myMethod = new VarargsFunction((arguments) => print(arguments));
}
main() {
var a = new A();
a.myMethod(1, 2, 3);
}
The second option allows to have code completion for myMethod and avoid a warning.
Is there way to overriding method in Dart like JAVA, for example:
public class A {
public void handleLoad() {
}
}
And when overriding:
A a = new A() {
#Override
public void handleLoad() {
// do some code
}
};
No, Dart does not have anonymous classes. You have to create a class that extends A and instantiate it.
No but it much less useful in Dart because you can just reassign function:
typedef void PrintMsg(msg);
class Printer {
PrintMsg foo = (m) => print(m);
}
main() {
Printer p = new Printer()
..foo('Hello') // Hello
..foo = ((String msg) => print(msg.toUpperCase()))
..foo('Hello'); //HELLO
}
However you will need some extra boilerplate to access instance.
Use type Function:
class A {
final Function h
A(this.h);
void handleLoad(String loadResult) { h(loadResult); }
}
Or
class A {
final Function handleLoad;
A(this.handleLoad);
}
A a = new A((String loadResult){
//do smth.
});
I was wondering if is possible to create an instance of a generic type in Dart. In other languages like Java you could work around this using reflection, but I'm not sure if this is possible in Dart.
I have this class:
class GenericController <T extends RequestHandler> {
void processRequest() {
T t = new T(); // ERROR
}
}
I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use "mirrorsUsed" if you don't want to have a 2-4MB js file.
This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:
You define a method type like this: (Add params if necessary)
typedef S ItemCreator<S>();
or even better:
typedef ItemCreator<S> = S Function();
Then in the class that needs to create the new instances:
class PagedListData<T>{
...
ItemCreator<T> creator;
PagedListData(ItemCreator<T> this.creator) {
}
void performMagic() {
T item = creator();
...
}
}
Then you can instantiate the PagedList like this:
PagedListData<UserListItem> users
= new PagedListData<UserListItem>(()=> new UserListItem());
You don't lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn't hurt.
You can use similar code:
import "dart:mirrors";
void main() {
var controller = new GenericController<Foo>();
controller.processRequest();
}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T();
T t = Activator.createInstance(T);
t.tellAboutHimself();
}
}
class Foo extends RequestHandler {
void tellAboutHimself() {
print("Hello, I am 'Foo'");
}
}
abstract class RequestHandler {
void tellAboutHimself();
}
class Activator {
static createInstance(Type type, [Symbol constructor, List
arguments, Map<Symbol, dynamic> namedArguments]) {
if (type == null) {
throw new ArgumentError("type: $type");
}
if (constructor == null) {
constructor = const Symbol("");
}
if (arguments == null) {
arguments = const [];
}
var typeMirror = reflectType(type);
if (typeMirror is ClassMirror) {
return typeMirror.newInstance(constructor, arguments,
namedArguments).reflectee;
} else {
throw new ArgumentError("Cannot create the instance of the type '$type'.");
}
}
}
I don't know if this is still useful to anyone. But I have found an easy workaround. In the function you want to initialize the type T, pass an extra argument of type T Function(). This function should return an instance of T. Now whenever you want to create object of T, call the function.
class foo<T> {
void foo(T Function() creator) {
final t = creator();
// use t
}
}
P.S. inspired by Patrick's answer
2022 answer
Just came across this problem and found out that although instantiating using T() is still not possible, you can get the constructor of an object easier with SomeClass.new in dart>=2.15.
So what you could do is:
class MyClass<T> {
final T Function() creator;
MyClass(this.creator);
T getGenericInstance() {
return creator();
}
}
and when using it:
final myClass = MyClass<SomeOtherClass>(SomeOtherClass.new)
Nothing different but looks cleaner imo.
Here's my work around for this sad limitation
class RequestHandler {
static final _constructors = {
RequestHandler: () => RequestHandler(),
RequestHandler2: () => RequestHandler2(),
};
static RequestHandler create(Type type) {
return _constructors[type]();
}
}
class RequestHandler2 extends RequestHandler {}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T(); // ERROR
T t = RequestHandler.create(T);
}
}
test() {
final controller = GenericController<RequestHandler2>();
controller.processRequest();
}
Sorry but as far as I know, a type parameter cannot be used to name a constructor in an instance creation expression in Dart.
Working with FLutter
typedef S ItemCreator<S>();
mixin SharedExtension<T> {
T getSPData(ItemCreator<T> creator) async {
return creator();
}
}
Abc a = sharedObj.getSPData(()=> Abc());
P.S. inspired by Patrick
simple like that.
import 'dart:mirrors';
void main(List<String> args) {
final a = A<B>();
final b1 = a.getInstance();
final b2 = a.getInstance();
print('${b1.value}|${b1.text}|${b1.hashCode}');
print('${b2.value}|${b2.text}|${b2.hashCode}');
}
class A<T extends B> {
static int count = 0;
T getInstance() {
return reflectClass(T).newInstance(
Symbol(''),
['Text ${++count}'],
{Symbol('value'): count},
).reflectee;
}
}
class B {
final int value;
final String text;
B(this.text, {required this.value});
}
Inspired by Patrick's answer, this is the factory I ended up with.
class ServiceFactory<T> {
static final Map<Type, dynamic> _cache = <String, dynamic>{};
static T getInstance<T>(T Function() creator) {
String typeName = T.toString();
return _cache.putIfAbsent(typeName, () => creator());
}
}
Then I would use it like this.
final authClient = ServiceFactory.getInstance<AuthenticationClient>(() => AuthenticationClient());
Warning: Erik made a very good point in the comment below that the same type name can exist in multiple packages and that will cause issues. As much as I dislike to force the user to pass in a string key (that way it's the consumer's responsibility to ensuring the uniqueness of the type name), that might be the only way.
Admittedly, this is a little bit of an odd test case, but it's a problem I've ran in to. I have a class that takes a function as a parameter in it's constructor. I'd like to know if the function that was passed was called. Here's an example:
class TestClassMock extends Mock implements RealClass {
RealClass _real;
TestClassMock() {
_real = new RealClass();
when(callsTo("myNamedFunction")).alwaysCall(_real.myNamedFunction);
}
}
class RealClass {
String _name = "RealClass";
Function myNamedFunction;
RealClass() {
myNamedFunction = _theNamedFunction;
}
String _theNamedFunction() {
return _name;
}
}
class ClassThatCallsRealClass {
ClassThatCallsRealClass(Function func) {
func();
}
}
//The test
TestClassMock testClassMock = new TestClassMock();
ClassThatCallsRealClass caller = new ClassThatCallsRealClass(testClassMock.myNamedFunction);
testClassMock.getLogs(callsTo("myNamedFunction")).verify(happenedOnce);
So to explain a bit, ClassThatCallsRealClass takes a function as a parameter and calls it. If you were to pass in (Instance Of RealClass).myNamedFunction, this would in turn call the private function _theNamedFunction on RealClass. However, if you try to mock RealClass and redirect all calls from myNamedFunction to the RealClass myNamedFunction, this seems to fail. I don't see any clear way to get this to work, but I would think it'd be possible.
Any ideas?
In Dart, all functions are instances of class Function as you know since you pass an instance of Function to the ClassThatCallsRealClass constructor. Instances of Function have a method call() as shown here.
Meanwhile, Dart has a very good mocking capability described here (with thanks to #KWalrath for the update).
So all you need to do is test with mocks like with any other object. Just as described in the reference, create a spy for ClassThatCallsRealClass and a mock for your Function instance. Then use a verify(happenedOnce) on the call() method of the function.
To mock your function do this:
class MockFunction extends Mock {
call(int a, int b) => a + b;
}
var mock = new MockFunction();
mock(1,2); //returns 3
Of course the parameter list to call will match that of the real function. Pass mock to your spy on ClassThatCallsRealClass.
That worked for me:
library x;
import "package:unittest/unittest.dart";
import "package:unittest/mock.dart";
class TestClassMock extends Mock implements RealClass {
RealClass _real;
TestClassMock() {
_real = new RealClass();
when(callsTo("myNamedFunction")).alwaysCall(_real.myNamedFunction);
}
}
class RealClass {
String _name = "RealClass";
Function myNamedFunction;
RealClass() {
myNamedFunction = _theNamedFunction;
}
String _theNamedFunction() {
return _name;
}
}
class ClassThatCallsRealClass {
ClassThatCallsRealClass(Function func) {
func();
}
}
class MyFunc implements Function {
Function func;
String functionName;
MyFunc(this.func, this.functionName);
call() {
var inv = new MyInvocation(functionName);
func(inv);
}
}
main(List<String> args) {
test('xx', () {
//The test
TestClassMock testClassMock = new TestClassMock();
ClassThatCallsRealClass caller = new ClassThatCallsRealClass(new MyFunc(testClassMock.noSuchMethod, "myNamedFunction"));
testClassMock.getLogs(callsTo("myNamedFunction")).verify(happenedOnce);
});
}
class MyInvocation extends Invocation {
final String f;
MyInvocation(this.f);
bool get isGetter => false;
bool get isMethod => true;
bool get isSetter => false;
Symbol get memberName => new Symbol(f);
Map<Symbol, dynamic> get namedArguments => {};
List get positionalArguments => [];
}
testClassMock.myNamedFunction returns null so I call noSuchMethod directly instead which needs an Invocation.
Invocation is abstract so I created an implemented.
MyFunc is a class that wraps the function. MyFunc can be called as a function because it implements the call method.