I am trying to get a way to call method on a generic type. But can't find it.
In swift I can write like:
protocol SomeGeneric {
static func createOne() -> Self
func doSomething()
}
class Foo: SomeGeneric {
required init() {
}
static func createOne() -> Self {
return self.init()
}
func doSomething() {
print("Hey this is fooooo")
}
}
class Bar: SomeGeneric {
required init() {
}
static func createOne() -> Self {
return self.init()
}
func doSomething() {
print("Hey this is barrrrrrr")
}
}
func create<T: SomeGeneric>() -> T {
return T.createOne()
}
let foo: Foo = create()
let bar: Bar = create()
foo.doSomething() //prints Hey this is fooooo
bar.doSomething() //prints Hey this is barrrrrrr
In Dart I tried:
abstract class SomeGeneric {
SomeGeneric createOne();
void doSomething();
}
class Foo extends SomeGeneric {
@override
SomeGeneric createOne() {
return Foo();
}
@override
void doSomething() {
print("Hey this is fooooo");
}
}
class Bar extends SomeGeneric {
@override
SomeGeneric createOne() {
return Bar();
}
@override
void doSomething() {
print("Hey this is barrrrr");
}
}
T create<T extends SomeGeneric>() {
return T.createOne();//error: The method 'createOne' isn't defined for the class 'Type'.
}
The code gives error The method 'createOne' isn't defined for the class 'Type'
How to fix this?. If this is possible, it would save lot of time and tons of lines of code.
It is not possible. In Dart you cannot call static methods through a type-variable because static methods must be resolved at compile-time and type-variables do not have a value until run-time. Dart interfaces are not Swift protocols, they can only specify instance methods.
If you want to parameterize a class with the ability to create a new object of a type, you need to pass a function doing so:
void floo<T>(T create(), ...) {
...
T t = create();
...
}
You cannot rely on the type variable alone for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With