Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics naming conventions

Tags:

java

generics

According to the Java documentation:

The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)

K - Key

N - Number

T - Type

V - Value

S,U,V etc. - 2nd, 3rd, 4th types

However , I have seen codes like this

public <R> Observable<R> compose(Transformer<? super T, ? extends R> transformer) {
        return ((Transformer<T, R>) transformer).call(this);
    }

Here it is using R, from what source can I find out what R means in here?

like image 271
WenChao Avatar asked Mar 31 '16 04:03

WenChao


People also ask

What letters do you use for generics?

Also, K is often used for a generic key type and V for a value type associated with it; in some cases E is used for the type of "elements" in a collection. Just to add - it's rare but occasionally you can use something more than letters for generic types.

Are generics Typesafe?

Generics were added to Java to ensure type safety. And to ensure that generics won't cause overhead at runtime, the compiler applies a process called type erasure on generics at compile time. Type erasure removes all type parameters and replaces them with their bounds or with Object if the type parameter is unbounded.

What is a generic type parameter in Java?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.

Can I use polymorphism in generics?

The polymorphism applies only to the 'base' type (type of the collection class) and NOT to the generics type.


1 Answers

"Result" or "return type." The former is particularly common in the JDK 8 classes.

Consider the JavaDocs for java.util.function.Function, for instance:

R - the type of the result of the function

The patterns <R> and , ?R> don't appear in OpenJDK 7's classes (citation: I downloaded the source and did a grep), but they do appear in several classes for building the Java toolchain itself, like javac. There, the R sometimes seems to stand for "result" and sometimes for "return type."

like image 116
yshavit Avatar answered Sep 23 '22 06:09

yshavit