蘇哲聖
蘇哲聖

Reputation: 795

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.

Upvotes: 3

Views: 881

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

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 }

Upvotes: 2

Anna Zubenko
Anna Zubenko

Reputation: 1663

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] 

Upvotes: 0

Related Questions