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

From the Kotlin documentation :

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

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

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

And the client code will say something like:

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

But I can’t be sure, because all this System.Type parameter seems redundant in the face of the type type parameter T in the method definition.

Also, in the same place on this page, what is 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 want to say typeof(Customer) , would you say Customer.class ? It is right?

What is class.java ?

+5
source share
1 answer

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

Kotlin, on the other hand, has a slightly stronger type system than Java, and since the function is built in there, the compiler knows what a generic type is (the reified keyword). The construction of T::class.java tells the Kotlin compiler to determine what the corresponding type of T , and then insert the class reference to T

This built-in redefinition is essentially the syntax sugar for Kotlin, allowing Kotlin users to delegate a hard-coded assignment type specification to the compiler output.

+7
source

All Articles