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
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
parameter seems redundant in the face of the generic type parameter
in the method definition.

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

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

I assume that the class
in Java is similar to
so if you wanted to say,
, you'd say
? Is that correct?



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.