比如说,有没有一个scala机制来简化长多态性边界?
case class RecordTypeX(...) extends A with B with C with D with E with F // defined in my project
case class RecordTypey(...) extends A with B with C with D with E with F // defined in a dependency package
class MyClass1[T <: A with B with C with D with E with F](x:T) {...}
class MyClass2[T <: A with B with C with D with E with F](x:T) {...}
...
val x = RecordTypeX(...)
val y = RecordTypeY(...)
val instance = new MyClass1(x)
val instance = new MyClass1(y)
理想情况下,如果能有一个类似于
type Processable=A with B with C with D with E with F
case class RecordTypeX(...) extends Processable // defined in my project
case class RecordTypeY(...) extends A with B with C with D with E with F // defined in a dependency package
class MyClass1[T <: Processable]() {...}
class MyClass2[T <: Processable]() {...}
...
val x = RecordTypeX(...)
val y = RecordTypeY(...)
val instance = new MyClass1(x)
val instance = new MyClass1(y)
有什么解决办法吗?
注:引入一个新的特质,结合所有其他的特质,并将其扩展到所有可能的类,如
trait Processable extends A with B with C with D with E with F
不能成为一个解决方案,因为我不能修改RecordTypeY。
你可以做到两者结合。
trait A
trait B
trait C
trait D
trait E
trait F
type Processable = A with B with C with D with E with F
trait ProcessableI extends A with B with C with D with E with F
final case class RecordTypeX(s: String) extends ProcessableI
final case class RecordTypeY(i: Int) extends A with B with C with D with E with F
class MyClass[T <: Processable](x: T)
val x = RecordTypeX("foo")
val y = RecordTypeY(3)
val instance1 = new MyClass(x)
val instance2 = new MyClass(y)