开发者

Seamless weaving of trait

I would like to automatically weave the definition of a new function say introduced by an extending trait Ext into an abstract class A:

class Base {
    abstract class A
    class B extends A
   开发者_如何转开发 case class C extends A   
}

trait Ext extends Base {
    trait A extends super.A {
        def say = "hello"
    }
}

object Test extends Base with Ext {
    val b = new B
    b.say
}

However, I obtain the following error:

<console>:12: error: value say is not a member of Test.B
           b.say

Any way of doing it?


It seems you are trying to use virtual classes, which is a feature not available in Scala.

Once A and B are defined they can't be redefined (like method overriding).

abstract class A
class B extends A

On the other hand, given your example, your objective could be achieved by a simple mixin. Here it is with few rewrites:

class Base {
    abstract class A
    class B extends A
    case class C extends A   
}

trait Ext extends Base {
    trait CanSay extends A {
        def say = "hello"
    }
}

object Test extends Base with Ext {
    val b = new B with CanSay
    def apply = b.say
}

Test.apply

No sure it will really help, but at least will help you understand what is going on.


Okay, as I said in a comment, it's not entirely clear what you're trying to do here, so I can't really try to suggest ways to do it. However, the approach you're using at the moment will not work.

Consider the class Hierarchy in this situation. At the base, we have A, which is then subclassed with B (in Base) and with Ext.A. These are not related save by their shared supertype, so you'll never find a say method on an instance of B.

The confusion possibly arises through the use of the word abstract. An abstract modifier on a class (even an inner class) does not make it an abstract member of the parent class, but denotes that it itself may have abstract members. There are ways of giving a class an abstract class member - through type parameters or type members. Unfortunately, you cannot derive from these AFAIK.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜