Details
Description
This idea was mentioned in a few mailing list posts:
http://archive.boo.codehaus.org/user/messages/530
http://archive.boo.codehaus.org/user/messages/558
http://archive.boo.codehaus.org/user/messages/559
(Rodrigo's response is not in the archives)
When a type in boo cannot be inferred, it resolves to "object". For example, this code will not work because "ToUpper()" is a method of type string, not type object:
l = [1,"asdf",3]
for item in l: //item's type is just "object"
if item isa string:
print item.ToUpper()
else:
print item
Currently you can cast to a string, which is fastest:
print (item as string).ToUpper()
or you can cast the item to a "duck" type so that the method resolution doesn't happen until runtime (this is slower):
for item as duck in l:
item.ToUpper() //now works if the item is really a string
We can create a compiler option to implicitly treat unknown types as type "duck" instead of type "object", so no "as duck" is necessary. This might be helpful for lighter scripting tasks where speed is not so important.
For example to make the above code sample work, in src/Boo.Lang.Compiler/TypeSystem/TypeSystemServices.cs, change the end of the GetEnumeratorItemType method (at line 424) from this:
return ObjectType;
to this:
return DuckType;
To make implicit duck typing optional, however, we would need to add the option to the Boo compiler (or else implement it as a compiler service like Rodrigo has discussed for other future options).
Three patches.
*Implement implict duck typing for all objects whose generic type is "object." This includes vague statements like "x as object" and when iterating through an Enumerable that returns an object.
*Implemeted booc.exe with a switch "-ducky" to toggle implicit duck typing behavior.
*Implemented "DuckByDefault" in CompilerParameters to make the two above patches work properly and nonintrusively.