Suppose I'm trying to write a function to return an instance of the current type. Is there a way to make T
refer to the exact subtype (so T
should refer to B
in class B
)?
class A {
<T extends A> foo();
}
class B extends A {
@Override
T foo();
}
I may not fully understood the question, but isn't it enough to just do this (notice casting to T):
then subclasses won't have to use overriding or covariance of types to make mother class methods return reference to them...
I found a way do this, it's sort of silly but it works:
In the top level class (A):
Assuming C extends B and B extends A.
Invoking:
Just write:
assuming you're using Java 1.5+ (covariant return types).
If you want something akin to Scala's
then no, this is not possible in Java. You should also note that there is not much you can return from a similarly typed function in Scala, apart from
this
.To build on StriplingWarrior's answer, I think the following pattern would be necessary (this is a recipe for a hierarchical fluent builder API).
SOLUTION
First, a base abstract class (or interface) that lays out the contract for returning the runtime type of an instance extending the class:
All intermediate extending classes must be
abstract
and maintain the recursive type parameterSELF
:Further derived classes can follow in the same manner. But, none of these classes can be used directly as types of variables without resorting to rawtypes or wildcards (which defeats the purpose of the pattern). For example (if
MyClass
wasn'tabstract
):This is the reason I refer to these classes as "intermediate", and it's why they should all be marked
abstract
. In order to close the loop and make use of the pattern, "leaf" classes are necessary, which resolve the inherited type parameterSELF
with its own type and implementself()
. They should also be markedfinal
to avoid breaking the contract:Such classes make the pattern usable:
The value here being that method calls can be chained up and down the class hierarchy while keeping the same specific return type.
DISCLAIMER
The above is an implementation of the curiously recurring template pattern in Java. This pattern is not inherently safe and should be reserved for the inner workings of one's internal API only. The reason is that there is no guarantee the type parameter
SELF
in the above examples will actually be resolved to the correct runtime type. For example:This example exposes two holes in the pattern:
EvilLeafClass
can "lie" and substitute any other type extendingMyBaseClass
forSELF
.self()
will actually returnthis
, which may or may not be an issue, depending on the use of state in the base logic.For these reasons, this pattern has great potential to be misused or abused. To prevent that, allow none of the classes involved to be publicly extended - notice my use of the package-private constructor in
MyBaseClass
, which replaces the implicit public constructor:If possible, keep
self()
package-private too, so it doesn't add noise and confusion to the public API. Unfortunately this is only possible ifSelfTyped
is an abstract class, since interface methods are implicitly public.As zhong.j.yu points out in the comments, the bound on
SELF
might simply be removed, since it ultimately fails to ensure the "self type":Yu advises to rely only on the contract, and avoid any confusion or false sense of security that comes from the unintuitive recursive bound. Personally, I prefer to leave the bound since
SELF extends SelfTyped<SELF>
represents the closest possible expression of the self type in Java. But Yu's opinion definitely lines up with the precedent set byComparable
.CONCLUSION
This is a worthy pattern that allows for fluent and expressive calls to your builder API. I've used it a handful of times in serious work, most notably to write a custom query builder framework, which allowed call sites like this:
The key point being that
QueryBuilder
wasn't just a flat implementation, but the "leaf" extending from a complex hierarchy of builder classes. The same pattern was used for the helpers likeWhere
,Having
,Or
, etc. all of which needed to share significant code.However, you shouldn't lose sight of the fact that all this only amounts to syntactic sugar in the end. Some experienced programmers take a hard stance against the CRT pattern, or at least are skeptical of the its benefits weighed against the added complexity. Their concerns are legitimate.
Bottom-line, take a hard look at whether it's really necessary before implementing it - and if you do, don't make it publicly extendable.
Manifold provides Java with the self type via the @Self annotation.
The simple case:
Use with generics:
Use with extension methods: