In Scala, how do I build a factory for nested types, outside of the containing class?
Explained with an example:
class A {
def f = {
开发者_JAVA百科 val b: B = C.factory(this).asInstanceOf[B]
}
class B
}
object C {
def factory(a: A): A#B = new a.B
}
C.factory
is a function for creating a new instance of an A#B
. Since B
is a nested type, I've included an A
reference in the function signature. The calling function f
has to cast the reference returned from factory
, which I'd like to avoid. Without the cast I get:
error: type mismatch;
found : A#B
required: A.this.B
It depends on what you want. In A
, B means this.B
, that is a B
that is created from the enclosing instance. Indeed your factory returns that, but it does not say so. It just says it returns the A#B
(called a type projection), a B
of some unspecified A
instance. If, for your val b, you don't care by which A instance it was created, then you should say so with val b: A#B (or let the compiler infer it).
If you do care that it is a B from your A and no other, you might be out of luck. Your factory
returns an instance of B
created by the a
parameter. But your signature does not says so. You would want a.B
rather than the less precise type projection A#B
. Alas, the language does not allow that. You will get an error illegal dependent method type: when you write a dependent type a.B
, a
must be a "stable identifier" and a method parameter is not considered one. Maybe this blog post may help
精彩评论