In Typescript, there is this concept of a polymorphic return type this
.
https://www.typescriptlang.org/docs/handbook/advanced-types.html#polymorphic-this-types
Example:
export abstract class Animal {
private name: string;
public setName(name: string): this {
this.name = name;
return this;
}
}
export class Dog extends Animal {
private breed: string;
public setBreed(breed: string): this {
this.breed = breed;
return this;
}
}
export class FluffyDog extends Dog {
private fluffiness: number;
public setFluffiness(fluffiness: number): this {
this.fluffiness = fluffiness;
return this;
}
}
export class Main {
constructor() {
const dog: FluffyDog = new FluffyDog()
.setName('Fluffy')
.setFluffiness(10)
.setBreed('Lab');
}
}
Is there anything equivalent in Java? The best I have come up with is:
public abstract class Animal<T extends Animal<T>> {
private String name;
public T setName(String name) {
this.name = name;
return (T)this;
}
}
class Dog extends Animal<Dog> {
private String breed;
public Dog setBreed(String breed) {
this.breed = breed;
return this;
}
}
class Main {
static {
Dog dog = new Dog()
.setName("Fluffy")
.setBreed("Lab");
}
}
OR this:
public abstract class Animal {
private String name;
public <T extends Animal> T setName(String name) {
this.name = name;
return (T)this;
}
}
class Dog extends Animal {
private String breed;
public <T extends Dog> T setBreed(String breed) {
this.breed = breed;
return (T)this;
}
}
class FluffyDog extends Dog {
private Long fluffiness;
public <T extends FluffyDog> T setFluffiness(Long fluffiness) {
this.fluffiness = fluffiness;
return (T)this;
}
}
class Main {
static {
FluffyDog dog = new FluffyDog()
.<FluffyDog>setName("Fluffy")
.setFluffiness(10L)
.setBreed("Lab");
}
}
The first seems to be only able to be subclassed once.
The second requires explicit type arguments in some situations.
Is there any way to return polymorphic this in Java?