Generics 具有相同特征但类型参数不同的组合

Generics 具有相同特征但类型参数不同的组合,generics,scala,Generics,Scala,我现在想知道如何为多个类型参数组合一个符合一个trait的对象/类/trait。 假设我有 trait Dependent[T]{ def observeCritereaChanged(oldValue:T, newValue:T):Unit } 例如,我希望能够为两个不同的类型参数定义一些实现依赖的特性 trait IntStrDependent extends Dependent[Int] with Dependent[String] 因此,myIntStrDependenttrai

我现在想知道如何为多个类型参数组合一个符合一个trait的对象/类/trait。 假设我有

trait Dependent[T]{
  def observeCritereaChanged(oldValue:T, newValue:T):Unit
}
例如,我希望能够为两个不同的类型参数定义一些实现依赖的特性

trait IntStrDependent extends Dependent[Int] with Dependent[String]
因此,my
IntStrDependent
trait的实例必须为这两种类型定义
ObserveCriteChanged

class MyDependent extends IntStrDependent {
  def observeCritereaChanged(oldValue:Int, newValue:Int) = //...
  def observeCritereaChanged(oldValue:String, newValue:String) = //...
}
到目前为止,我在尝试创建
IntStrDependent
特性时遇到了编译错误:

scala> trait IntStrDependent extends Dependent[Int] with Dependent[String]
<console>:8: error: illegal inheritance;
 self-type IntStrDependent does not conform to Dependent[Int]'s selftype Dependent[Int]
       trait IntStrDependent extends Dependent[Int] with Dependent[String]
                                     ^
<console>:8: error: illegal inheritance;
 self-type IntStrDependent does not conform to Dependent[String]'s selftype Dependent[String]
       trait IntStrDependent extends Dependent[Int] with Dependent[String]
                                                         ^
scala>trait IntStrDependent用Dependent[String]扩展Dependent[Int]
:8:错误:非法继承;
自类型IntStrDependent不符合Dependent[Int]的自类型Dependent[Int]
trait IntStrDependent使用Dependent[String]扩展Dependent[Int]
^
:8:错误:非法继承;
自类型IntStrDependent不符合从属[String]的自类型从属[String]
trait IntStrDependent使用Dependent[String]扩展Dependent[Int]
^

所以我的问题是:有没有一种方法可以完成我想做的事情(如果有,怎么做),或者这是一个失败的原因,因为Scala不是为完成这类事情而构建的?

好问题。我认为你不能直接做你想做的事

另一种方法是
trait IntStrDependent extends Dependent[other[Int,String]]
,但这并不能完全解决问题。也许迈尔斯·萨宾的一种变体可以让你做一些更有趣的事情

我认为最好的选择是保持简单

trait Dependent[T]{
  def observeCritereaChanged(oldValue:T, newValue:T):Unit
}

trait IntStrDependent {
  val I: Dependent[Int]
  val S: Dependent[String]
}

object MyDependent extends IntStrDependent {
  object I extends Dependent[Int] {
    def observeCritereaChanged(oldValue:Int, newValue:Int) {}
  }
  object S extends Dependent[String] {
    def observeCritereaChanged(oldValue:String, newValue:String) {}
  }
}
要使用
MyDependent
,必须明确选择
Int
String
变量,如中所示

MyDependent.I.observeCritereaChanged(1, 2)

在我看来,使类型依赖显式化无论如何都是一件好事。

这也是我通常做的事情。有趣的阅读您链接的内容。这肯定回答了我的问题,但我想我会同意你的方法:从
是一个
转换到
有一个
关系应该适合我的应用程序