String foo(Object o)Languages with run-time type information usually provide an additional, non-asserting means to test for a particular type at run-time, such as the Java instanceof binary operator, or the C# is binary operator. A type test in Ecstasy can be performed as an explicitly-left-associative operation:
{
return o.as(String); // could throw TypeMismatch
}
String foo(Object o)Normally, an object cannot be of a certain type, unless it is explicitly declared to be of that type. For example, even if the imaginary class FakeString has all of the same properties and methods as the String class, instances of FakeString cannot be cast to a String.
{
return o.is(String) ? o : "hello, world!";
}
Some languages do support such a thing, however. It's called duck typing, because "if it walks like a duck, and quacks like a duck, then it's a duck". An early prototype of Ecstasy had this feature for all types, and even provided a composition keyword, impersonates, to automate the composition of ducks and duck-like creatures. However, the capability did not mesh well with the design of the class-based portion of the type system, and was ultimately rejected for its unanswerable questions and potential incompatibilities.
Because duck typing is so useful, especially when working across the boundaries of loosely-coupled modules, one aspect of duck typing was explicitly retained: The ability to duck-type an interface. In many ways, an Ecstasy interface is simply a named type, i.e. a type plus a name. (This is not strictly true, but for this conversation, it will suffice.) And thus, in Ecstasy, one can make a Gosling Duck:
interface Duck
{
void waddle();
void quack();
}
class Gosling
{
void waddle() {}
void quack() {}
}
Duck foo(Gosling james)
{
return james;
}
(No ducks were harmed in the making of this blog entry.)
No comments:
Post a Comment
All comments are subject to the Ecstasy code of conduct. To reduce spam, comments on old posts are queued for review before being published.