7 Apr 2004 10:59
Re: [IDEA] auto-type coercion thoughts
On 7 Apr 2004, at 09:46, John Wilson wrote: > > On 7 Apr 2004, at 09:32, jastrachan@... wrote: > >> I've mused about this on and off at times over the last few months >> and Sam brought it up on IRC a little while ago so thought I'd >> mention it again... >> >> There's lots of fiddly methods to handle URL / File / InputStream / >> Reader etc. I've wondered if we should support some kind of >> auto-casting feature that types can support if they wish. >> >> e.g. >> >> class Object { >> toType(Class type) { >> if (type == String) { >> return toString() >> } >> return null >> } >> } >> >> then someone could do more clever implementations >> >> class Integer extends Number { >> toType(Class type) { >> switch (type) { >> case Long: >> return longValue() >> case Double: >> return doubleValue() >> } >> return super.toType(type) >> } >> } >> >> Similarly we could allow things like File / String / URL to be >> coerced into a Reader / InputStream. >> >> In terms of DefaultGroovyMethods - there's lots of redundancy. >> Particularly for the IO methods. We kinda wanna write lots of methods >> in term of (say) Reader and then mixin those methods to types like >> File, URL, InputStream, String without having to code all the >> implementations. >> >> This would allow types to decide what things they can be coerced >> into. e.g. allowing arrays and List to be auto-coerced if required. >> >> Thoughts? >> > > What happens when you pass one of these things as a parameter? > > class C { > void f(Type1 t) {..... > void f(Type2 t) {.... > } > > > x is not a subclass of either Type1 or Type2 but using toType magic > > Type1 a = x > > is allowed > > when I call c.f(x) is the conversion done and the function called? If > so how? Thats the idea, that if x.toType(Type1.class) returns non-null and x.toType(Type2.class) returns null (i.e. that x can be coerced to Type1 but not to Type2) then c.f(x) could be performed. If there is any ambiguity (e.g. there are 2 possible matching methods) then we throw an exception. Already we can have method ambiguity. e.g. f(String x, Object y) { ... } f(Object x, String y) { .. } f("hey", 1) // fine f(1, "hey") // fine f("oh", "dear") // ambiguous, throws exception Basically the coercion would only kick in if you were calling a method using dynamic dispatch and there were no matches, it'd allow the runtime to help you out and (say) coerce the Object[] into a List or coerce the URL/File/String into a Reader etc. James ------- http://radio.weblogs.com/0112098/
RSS Feed