How to use the Generics in the top-level function?

63 views
Skip to first unread message

vvakame

unread,
May 14, 2012, 2:47:49 AM5/14/12
to mi...@dartlang.org
Hello there.

I want to know about how to write a top-level function with generics.


I want to my library provide about type-safe test case.
for example.
expect("foobar").toBe(777); // error on compile-time. String is not int.

now, I wrote a this code.
Expection expect(var obj){
  return new _ExpectionImpl.expect(obj);
}

However, I want to write like this!
Expection<T> expect(T obj){
  return new _ExpectionImpl.expect(obj);
}

expect("hoge").toBe("hoge");
                 ↑ return 'Expection<String>' type.

but I can't done it.
Do you know a some solutions? I need a some advice.

real code is here.

regards.

Ladislav Thon

unread,
May 14, 2012, 3:06:38 AM5/14/12
to vvakame, mi...@dartlang.org
I want to know about how to write a top-level function with generics.

Dart doesn't have generic functions, so this isn't possible right now. You can star http://dartbug.com/254.

And BTW:

expect("foobar").toBe(777); // error on compile-time. String is not int.

Even if Dart had generic functions and expect would be one, this will never be a compile-time error. It would only fail at runtime in checked mode. Dart is a dynamically typed language in its heart, and type annotations mostly serve as a documentation (and programmers are encouraged to run their programs in checked mode, which checks these type annotations and fail at runtime when types don't match).

LT

vvakame

unread,
May 14, 2012, 8:37:31 AM5/14/12
to mi...@dartlang.org, vvakame
Thank you for your advice.

Dart doesn't have generic functions, so this isn't possible right now. You can star http://dartbug.com/254.

I just added a star now. I hope this feature to be implemented.
 
Even if Dart had generic functions and expect would be one, this will never be a compile-time error. It would only fail at runtime in checked mode. Dart is a dynamically typed language in its heart, and type annotations mostly serve as a documentation (and programmers are encouraged to run their programs in checked mode, which checks these type annotations and fail at runtime when types don't match).

Oh, is that so. I didn't know that checked mode works with type annotations.
I need a warning on the DartEditor; raise warning from code-analyzer if type mismatched. I'm writing a comment to Issue 254.

Regards.

2012年5月14日月曜日 16時06分38秒 UTC+9 Ladislav Thon:
Reply all
Reply to author
Forward
0 new messages