Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Generics return statement syntax

I'm struggeling to understand the syntax of this return statement, especially the leading C:

 <C>

I'm quite new to generics, but I know the basics. Can anyone explain this?

public abstract <C> CustomMap<K, C> map(Function<? super V, ? extends C> f)
like image 965
user1907859 Avatar asked Feb 10 '23 08:02

user1907859


1 Answers

<C> is not a return type. It's a declaration of a new generic type variable that can be used only by the map method.

Since the map method appears to have additional generic type variables - V and K - that are not declared in the same way as C, we can assume that V and K are declared as generic type variables at the class level (of the class that contains this method). If They are not, V and K will be treated as regular identifiers (i.e. the compiler will expect to find classes having the names V and K).

Based on the signature of your method and its return type (CustomMap), I can assume that this method belongs to some class that implements the Map<K,V> interface. It accepts a Function that receives an instance of type V and returns an instance of type C, so it's reasonable to assume that it converts a Map<K,V> to a Map<K,C> (i.e. the keys remain the same and the values are transformed).

like image 138
Eran Avatar answered Feb 28 '23 00:02

Eran