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
?
C is a programming language as we know . To solve any problem like take a example to add two numbers ,we can add but machine need some algorithm to perform any task.So ,by using these programming language you can write a code to solve these problem.So,this is coding in c.Example. //Addition of two numbers in c.
Programming in C forces you to learn memory allocation, data structures and types, how a computer treats and stores different kinds of data, and finally how to manage memory. These are things that you won't get to if you learn only a high-level language.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With