1

Looking at a library called mongojack 3.0 - https://github.com/mongojack/mongojack. This library contains a file called JacksonMongoCollection.java It has a method...

  public JacksonCollectionKey<TResult> getCollectionKey() {
        return new JacksonCollectionKey<>(getMongoCollection().getNamespace().getDatabaseName(), getMongoCollection().getNamespace().getCollectionName(), getValueClass());
    }

This returns JacksonCollectionKey<>

This library compiles fine.

I have not seen an empty generic type definition before. How does this work?

barrypicker
  • 9,740
  • 11
  • 65
  • 79
  • 2
    It's the [diamond operator](https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7). The type is already known since it's in the method signature, so you don't need to repeat it. – azurefrog Jan 21 '20 at 22:14
  • 1
    Did you do any research? See e.g. https://stackoverflow.com/q/8660202/3001761 – jonrsharpe Jan 21 '20 at 22:15
  • @jonrsharpe - yes, I researched but found a flood of how generics works. I didn't know it was called 'Diamond' operator, never heard of it. I suspect if I knew what to search on I wouldn't need to reach out for help. I appreciate your concern, however, as you seem overly helpful. Thank you. – barrypicker Jan 21 '20 at 22:17
  • I searched on "what does <> mean in Java", among others. – barrypicker Jan 21 '20 at 22:18

2 Answers2

2

Empty generic type brackets are used where generic type can be inferred from context by compiler. In your case, compiler will insert TResult into empty brackets.

ardenit
  • 3,610
  • 8
  • 16
2

This is a an example of "Type Inference" in Java. In certain situations, explicit type information can be omitted, when it is otherwise obvious what the missing type is.

In your example, the method returns JacksonCollectionKey<TResult>, and as such, it is not necessary to specify the type parameter, since it is given by the return type.

Another common example is:

List<String> list = new ArrayList<>();
cameron1024
  • 9,083
  • 2
  • 16
  • 36