Should it be possible to type-annotate Map literals?

4 views
Skip to first unread message

Olov Lassus

unread,
Oct 24, 2011, 4:28:30 PM10/24/11
to mi...@dartlang.org
If we provide type information when instantiating a new Map, we get
runtime type-checking (VM, checked mode):
var m1 = new Map<String, int>();
m1["str"] = "hello"; // error: type OneByteString is not assignable
to type int
m1[1] = 2; // error: type Smi is not assignable to type String

I can't get the same behavior if I use Map literals, neither in the
literal initializer nor in subsequent []= operations. No exception
gets thrown for these two lines:
var m2 = <String, String>{"a": 0}; // Map literal doesn't type-check values
m2[2] = 1; // nor does []= (for keys or values)

Is it possible to type-annotate Map literals and if so, how?

I understand that Dart restricts Map literal keys to Strings and that
those are already checked ("map entry key must be string literal").

/Olov

Bob Nystrom

unread,
Oct 24, 2011, 4:50:30 PM10/24/11
to Olov Lassus, mi...@dartlang.org
On Mon, Oct 24, 2011 at 1:28 PM, Olov Lassus <olov....@gmail.com> wrote:
If we provide type information when instantiating a new Map, we get
runtime type-checking (VM, checked mode):
 var m1 = new Map<String, int>();
 m1["str"] = "hello"; // error: type OneByteString is not assignable
to type int
 m1[1] = 2; // error: type Smi is not assignable to type String

I can't get the same behavior if I use Map literals, neither in the
literal initializer nor in subsequent []= operations. No exception
gets thrown for these two lines:
 var m2 = <String, String>{"a": 0}; // Map literal doesn't type-check values
 m2[2] = 1; // nor does []= (for keys or values)

Is it possible to type-annotate Map literals and if so, how?

Yes, it should be. I believe what you're doing is correct and it should be giving you a warning in checked mode. Can you file a bug on it?
 

I understand that Dart restricts Map literal keys to Strings and that
those are already checked ("map entry key must be string literal").

Right. I think there's been some discussion of loosening that to serializable and/or const-able types but right now it just supports strings.

- bob

Olov Lassus

unread,
Oct 24, 2011, 5:09:54 PM10/24/11
to Bob Nystrom, mi...@dartlang.org
On Mon, Oct 24, 2011 at 10:50 PM, Bob Nystrom <rnys...@google.com> wrote:
>> Is it possible to type-annotate Map literals and if so, how?
>
> Yes, it should be. I believe what you're doing is correct and it should be
> giving you a warning in checked mode. Can you file a bug on it?

Issue 221: <http://code.google.com/p/dart/issues/detail?id=221>

/Olov

Bob Nystrom

unread,
Oct 24, 2011, 5:27:58 PM10/24/11
to Olov Lassus, mi...@dartlang.org
Thanks!

- bob
Reply all
Reply to author
Forward
0 new messages