Re: [Vala] Generics: constraints and 'new T ()' on type parameters?



Thanks for the reply.

class Factory {
   public static Foo make(Type type) {
         return Object.new (type) as Foo;
   }
}

A generic factory returning a base class means that the manufactured
object will require up-casting to access members not in the base
class. The following use of generics lets me state the type just once
when I create the factory. To my surprise it actually works.
Strangely, (<thing> as T) isn't allowed but make() still returns a
compile-time T without warnings.

class Factory <T> {
       public T make () {
               return Object.new (typeof(T));
       }
}

BTW: shouldn't a factory has one method for making each type of objects?

I think it's supposed to have a big switch statement and knowledge of
every object it can create. A factory may not be the correct pattern
to describe a table wrapper on a database. make () would be find (),
find_all(), and Factory itself could be called Crud or TableWrapper.
Foo is a tuple. Sorry if my generalization missed the mark.

-Sam Danielson



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]