Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
Water Cooler v2 Avatar asked Aug 18 '16 04:08

Water Cooler v2


People also ask

What is a code in C?

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.

Why would you code 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.


1 Answers

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.

like image 101
chrylis -cautiouslyoptimistic- Avatar answered Sep 25 '22 14:09

chrylis -cautiouslyoptimistic-