我真的很喜歡使用上限類型邊界來給我的結構可以採取一些靈活性。不過,我真的不知道它的任何背後的原理,因爲我用下面的代碼中找到:斯卡拉上限類型邊界和父類
object BoundsTest {
abstract trait Service
class Collection[T <: Service] extends collection.mutable.HashMap[Symbol, collection.mutable.Set[T]] with collection.mutable.MultiMap[Symbol, T]
type Actives[T <: Service] = collection.mutable.HashMap[Symbol, T]
class Library[T <: Service](collection: Collection[T], actives: Actives[T])
private val libraries = new collection.mutable.HashMap[Symbol, Library[Service]]
def setLibrary[T <: Service](name: Symbol, library: Library[T]) {
libraries += name -> library
}
}
我想,我的類可以,只要它的一貫使用的Service
的子類。然而,這不起作用:
$ scalac test.scala
test.scala:10: error: type mismatch;
found : com.bubblefoundry.BoundsTest.Library[T]
required: com.bubblefoundry.BoundsTest.Library[com.bubblefoundry.BoundsTest.Service]
Note: T <: com.bubblefoundry.BoundsTest.Service, but class Library is invariant in type T.
You may wish to define T as +T instead. (SLS 4.5)
libraries += name -> library
^
的問題是,我認爲,在如何(?何時)我定義libraries
,彷彿我做如下修改一切成功編譯:
// private val libraries = new collection.mutable.HashMap[Symbol, Library[Service]]
def setLibrary[T <: Service](name: Symbol, library: Library[T]) {
new collection.mutable.HashMap[Symbol, Library[T]] += name -> library
}
如何聲明libraries
HashMap,使其具有多個Library
s與Service
s不同?在這裏可以參考Service
還是不可能的?
還是我吠叫完了錯誤的樹?謝謝!