Type parameter does not extend given type

前端 未结 1 413
粉色の甜心
粉色の甜心 2021-02-05 11:12

I would like to define a generic such that its type parameter does NOT extend a given type.

For example,

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


        
相关标签:
1条回答
  • 2021-02-05 11:50

    You can do such a thing using implicits. Here's a trick from Miles Sabin on scala-language:

    // 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 讨论(0)
提交回复
热议问题