I have the following code snippet:
abstract class Foo[T <: Foo[T]] { self: T =>
def bar(x: T): T
def newFoo: Foo[T] = {
new Foo[T] { self: T =>
// ...
}
}
}
I have a need to generate a new instance of Foo within a method of my abstract class. Can anyone advise me on how best to approach this?
Thanks, Hadil
The self-type
self: T =>implies that yourFoo[T]must also be aT.new Foo[T] { ... }isn't an instance ofTfor any arbitraryTthat makes upFoo[T]. You also can't add a self-type to an anonymous class likenew Foo[T] { ... }, because it doesn't make sense. Either the concrete class is or isn't aTat that point.Constructing a method like
def newFoo: Foo[T]in a type-safe way isn't really possible with the self-type in place, because you'd need to know how to construct an arbitraryT. You might be able to do what you want with reflection, when eachThas the same constructor.This ceases to work when there are constructor parameters: