d - Array of concrete class not covariant with array of interface -
i'm having little problem in providing abstract base layer dataaccess.mysqlclient
module have defined bunch of interfaces minimum requirements , bunch of classes implement them.
now dmd compiler complains:
error: function dataaccess.mysqlclient.mysqlreader.columns of type @property mysqlcolumninfo[]() overrides not covariant dataaccess.dbclient.idbreader.columns of type @property idbcolumninfo[]() exit code 1
the relevant lines of code this:
idbreader:
interface idbreader { @property idbcolumninfo[] columns(); // ... }
mysqlreader:
class mysqlreader : idbreader { private mysqlcolumninfo[] _columns; @property public mysqlcolumninfo[] columns() {return _columns;} // ... }
there few ways work around compiler issue;
- declare concrete property of
idbcolumninfo[]
- wrap array in list class
and couple more if think bit longer. none of seem quite elegant though.
here come big questions:
- am overlooking simple?
- can arrays of implementations ever covariant arrays of interfaces?
also can't imagine reason compilers' complaint. there more complex structures in code have been compiling fine. if can explain why won't work is, that'd appreciated.
you have run problem of array covariance.
let's assume code compiled fine. now, consider following code:
class someothercolumninfo : idbcolumninfo {} idbreader reader = new mysqlreader(...); idbcolumninfo[] columns = reader.columns; columns[3] = new someothercolumninfo(); // ok
since array mutable, can overwrite elements instances of other idbcolumninfo
-derived classes. problem we're modifying private _columns
field of mysqlreader
. so, have someothercolumninfo
instance member of mysqlcolumninfo[]
array. thus, we've broken type system without using casts or other unsafe code. since compiler expected stop doing accident, refuse implicitly cast mutable arrays of classes arrays of other classes, if classes related.
now, think make sense d allow compilation if returned array not mutable (that is, const or immutable). however, compiler doesn't either. don't know if that's omission, or if there's reason unknown me.
Comments
Post a Comment