2011-10-16 34 views
14

我想定義一個泛型,使其類型參數不擴展給定類型。類型參數不擴展給定類型

例如,

trait myTrait[T <: Throwable] { 
    // .... 
} 

將定義其中其類型參數延伸Throwable的性狀。我想要類似(不是真正的Scala代碼):

trait myTrait[T Not(<:) Throwable] { 
    // .... 
} 

其中type類型參數不擴展Throwable。有沒有辦法在Scala中構建這樣的概念?

+3

有趣的你應該問; Miles Sabin _just_在scala語言列表中發佈了一個答案:「強制該函數返回某些內容(除Unit以外)」:http://groups.google.com/group/scala-language/browse_thread/thread/e1242dfa7d65f599 –

回答

21

你可以用implicits做這樣的事情。這裏是邁克爾薩賓關於scala語言的一個技巧:

// Encoding for "A is not a subtype of B" 
trait <:!<[A, B] 

// Uses ambiguity to rule out the cases we're trying to exclude 
implicit def nsub[A, B] : A <:!< B = null 
implicit def nsubAmbig1[A, B >: A] : A <:!< B = null 
implicit def nsubAmbig2[A, B >: A] : A <:!< B = null 

// Type alias for context bound 
type NOT[T] = { 
type Lambda[U] = U <:!< T 
} 

// foo does not accept T of type Unit 
def foo[T : NOT[Unit]#Lambda](t : T) = t 
+0

如果你已經使用'shapeless'庫,那麼你可以這樣做:'def foo [T:|¬| [Unit]#λ](t:T)= t'或者,在兩行中:type NotUnit [ T] = |¬| [Unit]#λ[T]'和'foo [T:NotUnit](t:T)= t' – VasyaNovikov