[Vala] nullable generic types
- From: Adam Dingle <adam yorba org>
- To: vala-list gnome org
- Cc: all yorba org
- Subject: [Vala] nullable generic types
- Date: Mon, 05 Apr 2010 14:10:23 -0700
I've noticed that Vala forces generic types to be non-nullable when
instantiated with a primitive type. For example:
public class List<T> {
public T? abc() { return null; }
public bool def(T? t) { return t == null; }
}
void main() {
List<int> list = new List<int>();
int? i = list.abc(); // i receives the value 0, not null
bool b = list.def(null); // compiler error: cannot convert from null
to int
}
Is this behavior by design? I suspect that it is: this allows the
compiler to generate only one copy of List<T> and use it for all
instantiations including both reference and primitive types. If this is
a compromise by design, I think that it's a reasonable one, though it
would be nice to know whether we can expect this behavior to remain the
same in the future. :)
The above has a practical consequence when using generic collections:
HashMap<int, int> m = ...;
int? i = m.get(5);
Now i receives the value 0 (not null) if the element is absent.
On a related note, I've noticed that 'valac --vapi' makes generic types
non-nullable. If I generate a VAPI file for the List class above it
looks like this:
public class List<T> {
public List ();
public T abc ();
public bool def (T t);
}
Is this a bug? Conceivably the nullable types are erased in the VAPI
file as a warning to callers that they will not actually be nullable
when the class is instantiated with a primitive type, given the behavior
above. But there doesn't seem to be much point to that, since callers
must expect this same behavior when nullable types are present in a
generic class anyway, even one which is not defined via a VAPI file. Is
there some other reason why the types should not be nullable in the VAPI
file?
adam
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]