[英]Generics in Scala: implementing an interface/trait twice?
給定一個通用接口,如下所示
interface I<T> {
void m(T t);
}
我可以在C#中創建一個類,它使用為T提供的不同類型實現兩次(或更多次),例如
class C : I<int>, I<String> {
public void m(int i) { }
public void m(String s) { }
}
由於擦除泛型類型信息,這在Java中無法完成,但是在Scala中可以實現這樣的事情嗎?
在同一性狀號混合只可能在Scala中,如果2種類型與該性狀(接口)與符合彼此和所述性狀沒有直接兩次混入同一類類型參數化。 為確保兩種類型相互一致,通常必須使類型參數協變( +
)。
例如,這是不允許的:
scala> trait A[+T] { def foo: T = sys.error() }
defined trait A
scala> class C extends A[AnyRef] with A[String]
<console>:8: error: trait A is inherited twice
class C extends A[AnyRef] with A[String]
但這是:
scala> trait A[+T] { def foo: T = sys.error() }
defined trait A
scala> class C extends A[AnyRef]
defined class C
scala> class B extends C with A[String]
defined class B
請注意,在這種情況下,您將不會像C#那樣獲得重載語義,但是重寫語義 - A
具有符合簽名的所有方法將在一個具有最特定簽名的方法中融合,根據方法選擇方法線性化規則 ,而不是每次混合特征時都有一個方法。
不,它不能。 一般來說,我在這種情況下做的是
class C {
object IInt extends I[Int] { ... }
object IString extends I[String] { ... }
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.