简体   繁体   中英

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

I want to write code like this:

trait A[S]
class B {
    class BI
}
class C(val b: B) extends A[b.BI] // won't compile

Which won't compile. So I write this:

class C[BI0] private (val b: B) extends A[BI0]
object C {
  def apply(b: B): C[b.BI] = new C(b)
}

But that looks ugly. Is there a better implementation?

Why do I have this question? I conceive a example:

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 = {}
}

I don't want to use CarFactory#Car because this car store only sell cars of the factory factory .

I don't think there's a better way. What you have is a fairly standard way of working around using path-dependent types in class declarations. Alternatively, you can use type members:

trait A { type S }

class B { class BI }

class C(val b: B) extends A { type S = b.BI }

I'm not entirely sure what are you trying to do here, but does this work for you?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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