2010-01-20 84 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)