开发者

Actionscript Duck-typing

I'm overriding a protected function in a subclass.

Let's say I ha开发者_运维技巧ve two classes, Apple and Fruit. I have all variables in place, this is just a simplified version.

class FruitBasket
   protected function getRandom():Fruit
    {
        // return random piece of fruit
    }

class AppleBasket extends FruitBasket
   protected override function getRandom():Apple
    {
        // return random apple
    }

class Fruit

class Apple extends Fruit

Example is trivial. The problem is that the type of the getRandom function depends on its own type. One returns an apple, the other returns a fruit. Of course I get errors about override and coercion.

I've tried returning a Fruit instead of an Apple, but then the object is not an apple, therefore it has no Apple-specific properties. The problem is in ducktyping. There's a third class I cannot change, that executes the getRandom() function on each object, and I need the Apples to be something slightly different.

How can I override the getRandom function in Apple, so that it returns apples, rather than fruit?


This is a circle-ellipse problem. I would simply not override the function; rather I would rename the function to be more specific. So rename it to getRandomApple() in AppleBasket. Your semantics are getting a little muddy so I would make things separate and clearer.

It's too bad you can't change the function name in FruitBasket, because I would change that to getRandomFruit() to make the semantics clearer.


The equivalent to duck typing in AS3 would be the "*" or "Object" type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜