20091019

Support for generator type conversion in Quickcheck

A new utility method is now part of Quickcheck that lets you convert a Generator<A> to a Generator<B> given that A extends B.

This is useful when you have a Generator<Integer> and would like to treat it as a generator of type Generator<Object>.

This can now be done using the Generators.cast method:
Generator<Integer> integers = PrimitiveGenerators.integers();
Generator<Object> objects = Generators.<Object> cast(integers);
This is valid as the type Generator is covariant. (It does only produce values but the state of the Generator<T> is not altered.)

The cast is needed as the Java type does only support invariant generic types. Java cannot support the valid implicit type conversion from Generator<Integer> to Generator<Object>. This information is not present in the Java type system. The cast has to be performed explicitly. (If the generic type Generator could be annotated that it is covariant this sort of conversion could be supported. Scala supports the covariant and contravariant type conversion this way.)

No comments:

Post a Comment

Post a Comment