in Dart, problems with static method when called from variable - class

have class Klass with static method fn1
class Klass {
static String fn1() => 'hello';
}
> Klass.fn1(); // hello
but when Klass is assigned to a variable, calling the method fn1 fails
var k = Klass;
> k.fn1() // "Unhandled exception: Class '_Type' has no instance method 'fn1'.
don't quite know what's going on here

A simple workaround
class Klass {
static fn1(String name) {
return name;
}
fn1NonStatic(String name) {
return fn1(name);
}
}
Klass().fn1NonStatic("test");

I'm not sure what the intent of the code here is, but you might want to use dart:mirrors to reflectively call fn1(). I don't believe you can invoke it by assigning Klass to a variable. Here is how you can do it:
import 'dart:mirrors';
class Klass {
static String fn1() => 'hello';
}
main() {
final mirror = reflectClass(Klass);
print(mirror.invoke(#fn1, []).reflectee); // Prints 'hello'.
}

Related

how to get the extender or implementer child's Type

I have a class:
abstract class Foo {
String getName(T f);
}
and:
class Bar implements Foo {}
or
class Bar extends Foo {}
how can Foo know Bar and implement T as Bar?
UPDATE:
I considered statically passing the type of the child, like:
#override
String getName<Bar>(Bar p1) {
return p1.name;
}
this way I ran into this error: The property 'name' can't be unconditionally accessed because the receiver can be 'null'. Try making the access conditional (using '?.') or adding a null check to the target ('!').
so, I edited it to be:
#override
String getName<Bar>(Bar p1) {
return p1!.name;
}
and now I'm getting this error: The getter 'name' isn't defined for the type 'Bar & Object'. Try importing the library that defines 'name', correcting the name to the name of an existing getter, or defining a getter or field named 'name'.
I guess the only solution, for now, is using dynamic type, like this:
abstract class Foo {
String getName(f);
}
and
class Bar implements Foo {
#override
String getName(f) {
return (f as Bar).name;
}
}
but I'd really like to know the answer to this question.
abstract class Foo {
String getName(T f);
}
should not be valid. T is not specified anywhere.
You need to specify a place for the generic to be passed:
abstract class Foo<T> {
String getName(T f);
}
Then pass that generic when you extend/implement the abstract class:
abstract class Foo<T> {
String getName(T f);
}
class Bar implements Foo<Bar> {
final String name = '';
#override
String getName(Bar p1) {
return p1.name;
}
}
If getName will always accept an implementer of Foo, you can remove the generic and instead use the covariant keyword:
abstract class Foo {
String getName(covariant Foo f);
}
class Bar implements Foo {
final String name = '';
#override
String getName(Bar p1) {
return p1.name;
}
}

How to override a Dart method on instantiation? [duplicate]

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.
});

Why can't print any statement outside the method body in class in dart

class Car {
var name;
var model;
var cc;
Car(this.name, this.model, this.cc);
printAll() {
print(name);
print(model);
print(cc);
}
print(name); //Showing Error
}
void main() {
var obj = Car("Marcedes", "Class E", 5000);
obj.printAll();
}
Why i can't do any kind of operation outside the method body. The code generates error in compilation which given bellow. The code write in Dartpad.
Error in Compilation. The output show
Error compiling to JavaScript:
main.dart:1:7:
Error: The non-abstract class 'Car' is missing implementations for these members:
You have declared a method named print with a parameter called name but without a method body, i.e. an abstract method. In order to instantiate a class, Dart obviously has to know what the method body is, therefore you cannot instantiate an abstract class.
You need to do two things:
Because you have an abstract method, and abstract methods are only allowed in abstract classes, you need to mark Car as abstract.
You need to create a subclass of Car that overrides print with an implementation, and then instead instantiate that class.
Something like this:
abstract class Car {
var name;
var model;
var cc;
Car(this.name, this.model, this.cc);
printAll() {
print(name);
print(model);
print(cc);
}
print(name); // Abstract method `print` with no implementation
}
class ConcreteCar extends Car {
ConcreteCar(name, model, cc): super(name, model, cc);
#override
print(name) {
// Implementation of `print`
}
}
void main() {
var obj = ConcreteCar("Mercedes", "Class E", 5000);
obj.printAll();
}
Note: I left the implementation of print empty because I didn't understand the reason for the abstract print method and what the goal of the design is. But it should be trivial for you to fill out the missing pieces.

Dart: Referring to Singleton class from within itself

I have a singleton class and I would like to refer to it from within itself, however I am getting a CyclicInitializationError (Reading static variable 'instance' during its initialization) when trying to do so.
Here is an example:
void main(){
Singleton newSingleton = Singleton();
print(newSingleton.member);
}
class Singleton {
static final instance = Singleton._internal();
Singleton._internal();
factory Singleton(){
return instance;
}
String member = "hello";
String hamburger = instance.member; // This line causes the error to be thrown
}

Tell me the flow of execution in the following scenario

public class Temp
{
List<T> values = new List<T>;
static Temp()
{
System.Console.WriteLine("static constructor");
}
public Temp()
{
System.Console.WriteLine("general constructor");
}
}
Also please explain me when will the List object will be created and with what type it is created.
}
It appears the field gets initialized first, then the static constructor is called, then the constructor.
class Test
{
string variable = new Func<string>(() =>
{
Console.WriteLine("field initializer");
return "VARIABLE";
})();
static string staticvariable = new Func<string>(() =>
{
Console.WriteLine("static field initializer");
return "STATICVARIABLE";
})();
static Test()
{
System.Console.WriteLine("static constructor");
}
public Test()
{
System.Console.WriteLine("general constructor");
}
}
Test t = new Test();
outuput:
static field initializer
static constructor
field initializer
general constructor
[edit]
Oops sorry, it was a non-static field and I didn't notice it.
The static ctor will be called first.
Then values list will be second and the the ctor.
Read about beforefieldinit here.