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

后端 未结 7 1677
悲&欢浪女
悲&欢浪女 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<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");
    
    0 讨论(0)
提交回复
热议问题