Dart Class Map

I am porting some Java code to Dart and make heavy use of these kinds of maps:

Map<Class<? extends SomeClass>, SomeOtherClass> map = new HashMap<>();

At the moment, this seems impossible in the dart. I know that there is a proposal to introduce first-level types: http://news.dartlang.org/2012/06/proposal-for-first-class-types-in-dart.html , which will be introduced

class Type {
    @native String toString();
    String descriptor(){...} // return the simple name of the type
}

So, until this proposal is implemented, I created the following class:

class Type {
    final String classname;
    const Type(this.classname);
    String descriptor() => classname;
}

and the classes in which I need it have a simple get method

abstract Type get type();

That way, I can use mine Typeas if I used the real one Type, and to switch later I just needed to remove my workaround.

: - ( ), , , Type?

Dart 1.0

:

var map = new Map<Type, SomeOtherClass>();
// either
map[SomeOtherClass] = new SomeOtherClass();
// or
var instance = new SomeOtherClass();
map[instance.runtimeType] = instance;
+5
1

: Dart

Map<Class<? extends SomeClass>, SomeOtherClass>

.type/.class, ( , , , , ).

Map<? extends SomeClass, SomeOtherClass>

 Map<SomeClass, SomeOtherClass> aMap;

Dart, , SomeClass, SomeClass. , :

main() {
  Map<Test, String> aMap = new HashMap<Test, String>();
  var test = new Test("hello");
  var someTest = new SomeTest("world");
  var notATest = new NotATest(); 

  aMap[test] = test.msg;
  aMap[someTest] = someTest.msg;
  aMap[notATest] = "this fails";
}

class Test implements Hashable {
  Test(this.msg);

  int hashCode() => msg.hashCode();

  final String msg;
}

class SomeTest extends Test {
  SomeTest(String message): super(message);
}

class NotATest implements Hashable {
  int hashCode() => 1;
}

:

type 'NotATest' is not a subtype of type 'Test' of 'key'.
+4

All Articles