Is there a way to refer to the current type with a type variable?

后端 未结 7 1680
悲&欢浪女
悲&欢浪女 2020-11-22 03:01

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

7条回答
  •  渐次进展
    2020-11-22 04:04

    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");
    

提交回复
热议问题