I am little new to dart. I am trying to understand the difference between these two methods. Are both methods different or same? Where should I use one above another? Can someone explain it to me?
class A {
A.executor1() {
print('executor one is called');
}
static executor2() {
print('executor two is called');
}
}
Meanwhile neither of the method call is required to make a new instance? both are called using the class name.
void main() {
A.executor1(); // Will print "executor one is called"
A.executor2(); // Will print "executor two is called"
}
A.executor1() is a named constructor. static executor2() is a static method.
With an IDE (or dartpad.dev) you can see the different return types when you are placing the cursor over each method:
void main() {
A.executor1(); // (new) A A.executor1()
A.executor2(); // dynamic executor2()
}
static methods can be called without creating an instance of the class. executor1 will have access to this and so on because it's attached to an actual instance, but static methods will not because they aren't attached to anything.
Consider (in Javascript):
class Bicycle {
static numWheels = 2;
constructor(color) {
this.color = color;
}
static numberOfWheels() {
console.log(`Every bike has ${this.numWheels} wheels.`);
}
myColor() {
console.log(`This bike is ${this.color}.`);
}
}
// property of an instance
new Bicycle('red').myColor();
// available for anyone!
Bicycle.numberOfWheels();
Related
class Student {
static void getDetails() {
print('Get details method of Student class');
}
}
class DartStudent extends Student {
static void getDetails() {
print('Get details method of DartStudent class');
}
}
void main() {
DartStudent.getDetails();
}
Output : Get details method of DartStudent class
Expected : Error. static method cannot be overriden.. or something wrong..
what's wrong with me?
getDetails() in DartStudent class is not overriding parent class's method?
You can't override static methods.
The two static methods you declared there are in fact two different static methods, not the same, overriden one.
Answer for a different question, but related:
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
Also check out Why shouldn't static methods be able to be overrideable?. It provides a thorough explanation of why static methods should not be overrideable in general.
I need to find a way to get an instance of DataProcessingEngine without calling it's constractor.
I am trying to find a way to do so using the registered DataProcessingEngine in composition object (please see the following code). But I could not find a way to do so.
Anyone have a suggestion? Thanks in advance.
public class Composer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<IDataProcessingEngine, DataProcessingEngine>(Lifetime.Singleton);
//DataProcessingEngine dataProcessing = compostion.Resolve<IDataProcessingEngine>()??//no resolve function exists in Umbraco.Core.Composing
SaveImagesThread(dataProcessingEngine);
}
public Task SaveImagesThread(IDataProcessingEngine dataProcessingEngine)//TODO - decide async
{
string dataTimerTime = WebConfig.SaveProductsDataTimer;
double time = GetTimeForTimer(dataTimerTime);
if (time > 0)
{
var aTimer = new System.Timers.Timer(time);
aTimer.Elapsed += new ElapsedEventHandler(dataProcessingEngine.SaveImages);
aTimer.Start();
}
return default;
}
}
For all of you who are looking for a way to call a function (that's defined in another class in your code, an Engine or ...) from the composer(where the app starts) and want to avoid calling this function's class' constractor. I've found another way to do so:
public class QueuePollingHandler
{
[RuntimeLevel(MinLevel = RuntimeLevel.Run)]
public class SubscribeToQueuePollingHandlerComponentComposer :
ComponentComposer<SubscribeToQueuePollingHandler>
{ }
public class SubscribeToQueuePollingHandler : IComponent
{
private readonly IDataProcessingEngine _dataProcessingEngine;
public SubscribeToQueuePollingHandler(IDataProcessingEngine
dataProcessingEngine)
{
_dataProcessingEngine = dataProcessingEngine;
SaveImagesThread(_dataProcessingEngine);
}
public void SaveImagesThread(IDataProcessingEngine
dataProcessingEngine)
{
....
}
}
And the logic explenation: You create a class (SubscribeToQueuePollingHandlerComponentComposer from the example) and define its base class to be ComponentComposer<Class_that_inherits_IComponent>.
And when you start the application you could see that it gets to the registered class' constractor (SubscribeToQueuePollingHandler constructor).
That's the way that I found to be able to call a function right when the application starts without needing to call its class constractor and actualy use dependency injection.
I'm get null returned when attempting to access a subclass static variable through a overridden subclass accessor:
library resource;
abstract class Resource
{
String name;
String description;
Resource(this.name, this.description);
Resource.map(Map data)
{
...
_getDb()[this] = data;
}
abstract Map _getDb();
}
class Skill extends Resource
{
static Map _skills = {}
Skill.map(Map data) : super.map(data);
Map_getDb()
{
return _skills;
}
}
import 'resource.dart'
void main() {
useVMConfiguration();
test('constructor', () {
Skill skill = new Skill.map({
'name': 'foo'
});
}
}
Here I'm trying to call _getDb() on the (hopefully) now constructed subclass in the super constructor. Despite _skills being instantiated, _getDb() returns null.
Is this possible?
EDIT:
_skills is not present when inspecting this at _getDb():
this Skill [id=0]
description "bar" [id=19]
name "foo" [id=18]
Your example has several flaws as DartEditor shows.
Map_getDb() is missing a space between Map and _getDb().
Is this only in your question or in the code you run too?
abstract Map _getDb(); is also a syntax error.
In Dart a method is made abstract when you don't provide an implementation (; instead of {})
After this fixes the code works fine.
I would like to use the nested Generics, like
class Class<List<T>> {
...
}
But always Dart Editor gives me alerts. How should I avoid these alerts?
Well, Dart Editor is right. This code doesn't make any sense. Without further information on what you are trying to do (don't hesitate to update your question), I am assuming you actually mean one of those:
class MyClass<T> {
List<T> listField;
// other stuff
}
Or maybe the list itself should be generic?
void main() {
MyClass<SomeCustomListClass<String>> instance = new MyClass();
}
class MyClass<T extends List<String>> {
T listField;
// ...
}
Or maybe everything has to be generic:
void main() {
MyClass<String, SomeCustomListClass<String>> instance = new MyClass();
}
class MyClass<TElement, TList extends List<TElement>> {
TList listField;
TElement _firstListElement;
// whatever that could be used for
}
I have created Guice binding annotations that allow me to bind two different instances of a class depending on the annotation e.g.:
bind(Animal.class).withAnnotation(Cat.class).toInstance(new Animal("Meow"));
bind(Animal.class).withAnnotation(Dog.class).toInstance(new Animal("Woof"));
I was hoping to be able to create a provider method that provides a List that is a dependency for one of my classes, but can't figure out how to use the annotations for this:
#Provider
List<Animal> provideAnimalList() {
List<Animal> animals = new ArrayList<Animal>();
animals.add(#Cat Animal.class); // No, but this is what I want
animals.add(#Dog Animal.class); // No, but this is what I want
return animals;
}
So I was assuming that I would just be able to use the annotations in the argument to add() method of the List... but no.
How should I be approaching this? It seems to me it would be simpler simply to new the two instances of the Animal class and maybe this is not how the binding annotations were meant to be used.
I'd appreciate comments on the best use of the binding annotations in this scenario.
Thanks
If it is really what you want, here a working solution :
public class AnimalModule extends AbstractModule {
#Override
protected void configure() {
bind(Animal.class).annotatedWith(Cat.class).toInstance(new Animal("Meow"));
bind(Animal.class).annotatedWith(Dog.class).toInstance(new Animal("Woof"));
}
#Provides
List<Animal> provideAnimalList(#Cat Animal cat, #Dog Animal dog) {
List<Animal> animals = new ArrayList<Animal>();
animals.add(cat);
animals.add(dog);
return animals;
}
public static void main(String[] args) {
List<Animal> animals = Guice.createInjector(new AnimalModule()).getInstance(Key.get(new TypeLiteral<List<Animal>>() {
}));
for (Animal animal : animals) {
System.out.println(animal);
}
}
}
Annotations :
#Retention(value = RetentionPolicy.RUNTIME)
#BindingAnnotation
public #interface Cat {
}
Output :
Animal{sound='Meow'}
Animal{sound='Woof'}
However :
Don't create specific annotations, seems unnecessary in that case. Use #Named instead,
You may consider Multibindings to solve that problem.