Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method on generic type Dart

Tags:

generics

dart

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.

like image 861
Johnykutty Avatar asked Apr 29 '19 10:04

Johnykutty


1 Answers

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.

like image 123
lrn Avatar answered Oct 08 '22 19:10

lrn