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<Tree> children;
public List<@Self Tree> getChildren() {
return children;
}
}
public class MyTree extends Tree {
}
MyTree tree = new MyTree();
...
List<MyTree> children = tree.getChildren(); // :)
Use with extension methods:
package extensions.java.util.Map;
import java.util.Map;
public class MyMapExtensions {
public static <K,V> @Self Map<K,V> add(@This Map<K,V> thiz, K key, V value) {
thiz.put(key, value);
return thiz;
}
}
// `map` is a HashMap<String, String>
var map = new HashMap<String, String>()
.add("bob", "fishspread")
.add("alec", "taco")
.add("miles", "mustard");