簡體   English   中英

證明泛型類型的上限

[英]Prove upper type bound for generic types

我有一個類型類,我想用它來存儲對象的類型:

trait RetainType {
  type A
}

object RetainType {
  def apply[A0](): RetainType = new RetainType{
    type A = A0
  }
}

給定以下類別:

trait Annotation
class Entity extends Annotation

我希望編譯器證明RetainType.A擴展了Annotation

def hasAnnotation[A <: Annotation] = Unit

但是使用RetainType編譯器似乎無法解決此問題:

val retainType = RetainType[Entity]
hasAnnotation[RetainType.A] //throws an error: type arguments [retainType.A] do not conform to method hasAnnotation's type parameter bounds [A <: Annotation]

如果指定了類型,則可以正常工作:

hasAnnotation[Entity] //works fine

無論如何,編譯器可以證明這種關系?

您搞砸了RetainType.apply的簽名:

def apply[A0](): RetainType

返回類型未提及A0 ,因此被“遺忘”。 也就是說,在

val x = RetainType[Int]

xA是完全抽象的; 編譯器無法證明xA = Int因為apply的簽名刪除了該信息。 使用優化類型:

object RetainType {
  def apply[A0](): RetainType { type A = A0 } = new RetainType { override type A = A0 }
}

您可能要使用Aux模式來使其更適合使用:

object RetainType {
  type Aux[A0] = RetainType { type A = A0 }
  def apply[A0](): RetainType.Aux[A0] = new RetainType { override type A = A0 }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM