Home > Software engineering >  Does Java have a similar post method diamond operator that C# has?
Does Java have a similar post method diamond operator that C# has?

Time:05-11

The Unity project makes frequent use of C# functions that supply a type in a diamond operator after the method name. In the Unity source code it's defined like this:

public static T FindObjectOfType<T>() where T : Object
{
    return (T)FindObjectOfType(typeof(T), false);
}

An example of it's use:

CanvasRenderer canvas = FindObjectOfType<CanvasRenderer>();

My question is, does the Java language have a similar construct?

CodePudding user response:

Java has a similar construct, but the name "diamond operator" is reserved (ok, not really 'reserved', but used) for something slightly different.

In the construct

final List<String> stringList = new ArrayList<>();

the <> is called the "diamond operator" (although "diamond form" would be more correct), and it is a shortcut of the otherwise required term <String>.

Defining a method with a generic argument or return type looks in Java slightly different from C#:

public final <T,R> R doSomething( final T argument ) { … }

doSomething() takes an argument of type T and returns a result of type R, where R and T do not need to be distinct from each other.

Calling doSomething() may look like this:

final var date = LocalDate.now();
final String result = doSomething( date ); 

Your C# method FindObjectOfType<T>() would be declared in Java like this:

public final <T> T findObjectOfType( final Class<T> desiredType ) { … }

and it would be called like this:

CanvasRenderer canvas = findObjectOfType( CanvasRenderer.class );

CodePudding user response:

Yes. These diamond operators are called generics. Java has them too!

They use the same <> syntax. You can find more information online by searching for "java generics"

  • Related