This question already has answers here:
Dynamic class method invocation in Dart
(3 answers)
Closed 8 years ago.
I am wondering if there is anyway to call a function by its name in dart as in javascript.
I would like to do something as such:
foo["bar"]();
I don't want readers to think what the questioner wants isn't possible in Dart, so I'm adding an answer.
You need to use Mirrors to call a method if you have its name available as a string. Here is an example:
import 'dart:mirrors';
class Foo {
bar() => "bar";
}
void main() {
var foo = new Foo();
var mirror = reflect(foo);
print(mirror.invoke(#bar, []).reflectee); // Prints 'bar'.
}
Related
This question already has an answer here:
Smart cast (automatic type promotion) using 'is' is not working
(1 answer)
Closed 2 years ago.
I am working with dart without allowing implicit dynamics and casts and I noticed the following:
When working with a local variable, I can use a type check on that variable and if the test passes, the compiler will just assume that I can use that variable as that type:
var emp; // set to something
if (emp is Person) {
// The compiler infers that emp is a person within this scope
// so it allows me to use Person's member functions and variables
// without the need for explicit typecast
// https://dart.dev/guides/language/language-tour#type-test-operators
emp.firstName = 'Bob';
}
However, this does not work if the variable is the member variable of an object:
class SuperPerson {
Object _emp;
/* Various things that could be doing things with _emp here */
void memberFun() {
if (_emp is Person) {
_emp.firstName = 'Bob'; // ERROR: The setter firstName is not defined for type Object.
(_emp as Person).firstName = 'Bob'; // workaround but would like to avoid casts that could fail.
}
}
}
Why is that and how can I overcome it?
Could it be because of potentially other threads changing the value of _emp in between the test and the use?
Edit: I had forgotten that I had already answered this question. See that one instead.
(Since this answer had already been accepted at the time of this edit, I cannot delete it.)
This question already has answers here:
PHP Error : Fatal error: Constant expression contains invalid operations
(5 answers)
Closed 4 years ago.
I have the following code, where I get the error "PHP Fatal Error: Constant expression contains invalid operations". It works fine when I define the variable in the constructor. I am using Laravel framework.
<?php
namespace App;
class Amazon
{
protected $serviceURL = config('api.amazon.service_url');
public function __construct()
{
}
}
I have seen this question: PHP Error : Fatal error: Constant expression contains invalid operations
But my code does not declare anything as static, so that did not answer my question.
As described here
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
The only way you can make this work is :-
<?php
namespace App;
class Amazon
{
protected $serviceURL;
public function __construct()
{
$this->serviceURL = config('api.amazon.service_url');
}
}
Initializing class properties is not allowed this way. You must move the initialization into the constructor.
Another working alternative I used is with boot( ) with Laravel Eloquent:
<?php
namespace App;
class Amazon {
protected $serviceURL;
protected static function boot()
{
parent::boot();
static::creating(function ($model){
$model->serviceURL = config('api.amazon.service_url');
});
} }
This question already has answers here:
Why can't class fields be var? [duplicate]
(4 answers)
Closed 6 years ago.
Hey I'm trying to Define a mock database . I'm encountering an error while trying to equate var to Mock<'Repository'> The error is :
The contextual keyword 'var' may only appear within a local variable declaration Or In Script Code.
The Code that I have written is :
public class MockingDatabse
{
//Mock a Payment Info
var newPayment = new Mock<IPayment>();
}
I know that I can replace 'var' with 'Mock<"Repository">'. But I wanna know I'm not able to use
'var'
Try this:
public class MockingDatabse
{
//Mock a Payment Info
Mock<IPayment> newPayment = new Mock<IPayment>();
}
Coming from the java world I have difficulties to understand this code-fragment from the AngularDart pirate badge code lab:
Future _loadData() {
return _http.get('piratenames.json').then((HttpResponse response) {
PirateName.names = response.data['names'];
PirateName.appellations = response.data['appellations'];
});
}
}
From my understanding PirateName is a class and how can the line
PirateName.names = response.data['names'];
write a field of a class without referring to an actual instance?
Dart syntax allows static variables as does Java.
That is a static variable as defined in the source you provided Edit piratebadge.dart and you'll see where it is defined as static.
Say I have an instance of a class Foo, and I want to grab a list of all of its methods that are annotated a certain way. I want to have a reference to the method itself, so I'm not looking to use reflection to invoke the method each time, just to grab a reference to it the first time.
In other words, I want to do the reflection equivalent of this:
class Foo {
a() {print("a");}
}
void main() {
var f = new Foo();
var x = f.a; // Need reflective way of doing this
x(); // prints "a"
}
I have tried using InstanceMirror#getField, but methods are not considered fields so that didn't work. Any ideas?
As far as I understand reflection in Dart, there's no way to get the actual method as you wish to. (I'll very happily delete this answer if someone comes along and shows how to do that.)
The best I can come up with to ameliorate some of what you probably don't like about using reflection to invoke the method is this:
import 'dart:mirrors';
class Foo {
a() {print("a");}
}
void main() {
var f = new Foo();
final fMirror = reflect(f);
final aSym = new Symbol('a');
final x = () => fMirror.invoke(aSym, []);
x(); // prints "a"
}
Again, I know that's not quite what you're looking for, but I believe it's as close as you can get.
Side note: getField invokes the getter and returns the result -- it's actually fine if the getter is implemented as a method. It doesn't work for you here, but for a different reason than you thought.
What you're trying to get would be described as the "closurized" version of the method. That is, you want to get the method as a function, where the receiver is implicit in the function invocation. There isn't a way to get that from the mirror. You could get a methodMirror as
reflect(foo).type.methods[const Symbol("a")]
but you can't invoke the result.