2010-01-20 83 views
4

在Scala中,我怎样才能添加容器性状(如Traversable的[内容])到另一个延伸的容器(并因此限制了它的内容的可见度?依赖于性状遗传

例如,代码下面试图限定的性状WithIter用于需要Traversable的一个容器(当然,我有事实上其他事情在容器)

import scala.collection._ 

trait Container { 
    type Value 
} 

trait WithIter extends Container with immutable.Traversable[Container#Value] 

class Instance extends WithIter { 
    type Value = Int 
    def foreach[U](f : (Value) => (U)) : Unit = {} 
} 

编译器(scalac 2.8.0.Beta1-RC8)发现错误:

​​

有没有简单的方法?

回答

4
class Instance extends WithIter { 
    type Value = Int 
    def foreach[U](f : (Container#Value) => (U)) : Unit = {} 
} 

如果一个内部类说话的时候你不指定OuterClass#,然后this.(即实例特定)将被假定。

+0

我有点困惑的构造。你不能说:new Instance()。foreach((x:Int)=> x + 1)。你为什么要这样定义它? – 2010-01-20 15:03:05

+0

当您想要某些行为与Int类似但不兼容时(例如,如果您正在定义货币或度量单位),此构造可能很有用。 – 2010-01-20 16:10:28

+0

@Thomas:这不是_my_构造。鉴于问题的'WithIter'定义,这是声明'Instance'的正确方法。 – 2010-01-21 11:30:41

2

为什么你使用抽象类型?泛型是直截了当的:

import scala.collection._ 

trait Container[T] {} 

trait WithIter[T] extends Container[T] with immutable.Traversable[T] 

class Instance extends WithIter[Int] { 
    def foreach[U](f : (Int) => (U)) : Unit = {println(f(1))} 
} 


new Instance().foreach((x : Int) => x + 1)