泛型Scala中:实现一个接口/特质两次? [英] Generics in Scala: implementing an interface/trait twice?

查看:412
本文介绍了泛型Scala中:实现一个接口/特质两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于通用接口,如以下

interface I<T> {
    void m(T t);
}



我可以用C#创建一个实现我两次(或更多)一类对于T提供的不同类型,如:

I can in C# create a class that implements I twice (or more) with different types supplied for T, e.g.

class C : I<int>, I<String> {
   public void m(int i) { }
   public void m(String s) { }
}

这不能用Java来完成,由于泛型类型信息的删除,但这样的事情在Scala中可以实现吗?

This cannot be done in Java due to erasure of the generic type info, but can something like this be achieved in Scala?

推荐答案

没有。在相同的特质混合仅在斯卡拉可能的,如果2种与性状(接口)参数化与类型符合,彼此的特点是不混合到同一个类两次<强>直接。为了保证2种类型相互符合,你一般会不得不作出的类型参数协( + )。

No. Mixing in the same trait is only possible in Scala if the 2 types with which the trait (interface) is parametrized with types that conform to each other and the trait is not mixed into the same class twice directly. To ensure that the 2 types conform to each other, you will generally have to make the type parameter covariant (+).

例如,这是不允许的:

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你不会得到的重载的语义与C#的情况,但在覆盖语义 - 在所有的方法 A 与符合签名将在一种方法中,根据线性的规则,而不是每次你混合特质时间的一种方法。

Note that in this case you will not obtain the overloading semantics as is the case with C#, but the overriding semantics - all the methods in A with the conforming signature will be fused in one method with the most specific signature, choosing the method according to linearization rules, rather than having one method for each time you've mixed the trait in.

这篇关于泛型Scala中:实现一个接口/特质两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆