繁体   English   中英

scala类使用泛型扩展特征,泛型是一种字段

[英]scala class extend a trait with generic which is a type of a field

我想写这样的代码:

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 }

我不完全确定你在这里做什么,但这对你有用吗?

trait A[S] 
class B {
  class BI
} 
class C(val b: B) extends A[B#BI] 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM