Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure type in a generic implements some operators in Dart?

Tags:

generics

dart

I want to build a generic class which contains objects of type T. The containing class must execute some operators on these objects, specifically operators like +, -, * and /. How can I ensure that the objects' type implements these operators?

Specifically, I'm implementing a matrix class, as in mathematical matrices. I could have allowed only double elements, but I want to be able to also make matrices of custom numeric classes like rational numbers or complex numbers (this is part of a larger project).

My current implementation has the signature

class Matrix<T extends MatrixElement> {
  final int _rows;          // The number of rows
  final int _cols;          // The number of columns
  ...
  final List<T> _elements;  // Matrix data, [i*step+j] is row i, col j.

Where MatrixElement is an abstract class with operators like

dynamic operator + (dynamic other);

I could have changed the Matrix class to simply class Matrix<T> { ... }, but then errors can arise at runtime and Dart Editor is filled with warnings about the operators not being defined for the class Object.

What my intuition says is something like class Matrix<T implements MatrixElement> { ... }, but Dart doesn't seem to support this.

like image 703
Mikke Avatar asked Oct 22 '22 02:10

Mikke


1 Answers

I think the best you can do is just assume that the elements have these methods and leave the type parameter unbounded. That will get rid of the warnings, though it's probably a bit unsatisfying when you want the type system to help you out.

Union types would help, so here's the bug you can star: http://dartbug.com/4938

like image 51
Justin Fagnani Avatar answered Oct 24 '22 13:10

Justin Fagnani