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
Manifold provides Java with the self type via the @Self annotation.
The simple case:
public class Foo {
public @Self Foo getMe() {
return this;
}
}
public class Bar extends Foo {
}
Bar bar = new Bar().getMe(); // Voila!
Use with generics:
public class Tree {
private List children;
public List<@Self Tree> getChildren() {
return children;
}
}
public class MyTree extends Tree {
}
MyTree tree = new MyTree();
...
List children = tree.getChildren(); // :)
Use with extension methods:
package extensions.java.util.Map;
import java.util.Map;
public class MyMapExtensions {
public static @Self Map add(@This Map thiz, K key, V value) {
thiz.put(key, value);
return thiz;
}
}
// `map` is a HashMap
var map = new HashMap()
.add("bob", "fishspread")
.add("alec", "taco")
.add("miles", "mustard");