我想写这样的代码:
trait A[S]
class B {
class BI
}
class C(val b: B) extends A[b.BI] // won't compile
这不会编译。 所以我这样写:
class C[BI0] private (val b: B) extends A[BI0]
object C {
def apply(b: B): C[b.BI] = new C(b)
}
但这看起来很难看。有没有更好的实现方式?
为什么我有这个问题?我设想一个例子:
trait Store[Goods] {
def sell(goods: Goods): Unit
}
class CarFactory {
def make(): Car = new Car
class Car
}
class CarStore(val factory: CarFactory) extends Store[factory.Car]{//can't compile
def sell(car: factory.Car): Unit = {}
}
我不想使用 CarFactory#Car
因为这家汽车商店只卖工厂 factory
的汽车。
最佳答案
我认为没有更好的方法。您所拥有的是一种在类声明中使用依赖于路径的类型的相当标准的工作方式。或者,您可以使用类型成员:
trait A { type S }
class B { class BI }
class C(val b: B) extends A { type S = b.BI }
关于scala 类使用泛型扩展特征,泛型是字段的一种类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361666/