Water Cooler v2 Water Cooler v2 - 3 months ago 13
Java Question

Could you please explain this piece of code in terms of C# code?

From the Kotlin documentation page:

// public final class Gson {
// ...
// public <T> T fromJson(JsonElement json,
// Class<T> classOfT)
// throws JsonSyntaxException {
// ...


In the code snippet above, I understand everything except that
Class<T>
thing. I assume it is the C# equivalent of the following:

public sealed class Gson
{
public T FromJson<T>(JsonElement json,
System.Type Type)
{
}
}


And the client code would say something like:

var gson = new Gson();
var customer = gson.FromJson<Customer>(json, typeof(Customer));


But I can't be sure because that whole
System.Type
parameter seems redundant in the face of the generic type parameter
T
in the method definition.

Also, at the same location on that page, what's that
class.java
in the following snippet?

inline fun <reified T: Any> Gson.fromJson(json):
T = this.fromJson(json, T::class.java)


I assume that the class
Class
in Java is similar to
System.Type
so if you wanted to say,
typeof(Customer)
, you'd say
Customer.class
? Is that correct?

What's
class.java
?

Answer

Java has generic type erasure: The actual type T is not available to code at runtime. Since Gson needs to know what the target deserialization type is, passing the Class<T> explicitly identifies it.

Kotlin, on the other hand, has a somewhat stronger type system than Java, and since the function there is inlined, the compiler knows what the generic type actually is (the reified keyword). The construct T::class.java tells the Kotlin compiler to determine what the appropriate type T is and then inline the class reference to T.

This inline redefinition is essentially syntactic sugar for Kotlin, allowing Kotlin users to delegate the hardcoded specification of the destination type to the compiler's inference.

Comments