Kotlin generic strength analysis

1, What is generics
1. Generalized type or abstract type
2. An approximate implementation of duck type in static language

2, Implementation mechanism of generics
1. What is true generics? (C#)
2. What is pseudo generic? (Java,Kotlin)

3, Let's first look at the pseudo ubiquity in JAVA and Kotlin

But in C ා language, it is a true generics. It exists not only in compile time, but also in runtime. It has no problem.

4, Defining generic classes and generic methods in kotlin

package com.test

/**
 * @author:wangdong
 * @description:generic paradigm
 */

/**
 * Declare generics for functions
 * Define a method to find the maximum value of two numbers
 * So these two numbers must first be able to compare
 * Parameter type is T, return value is T
 * <T: Comparable<T>> T The upper bound of a type is comparable, and < T > is an argument
 */
fun <T: Comparable<T>> maxOf(a:T,b:T): T{
    return if (a < b) b else a
}

fun main(args: Array<String>) {
    val a = 5
    val b = 8
    val c = maxOf(a,b)
    println(c)

    val complex = Complex(3.0,2.4)
    val complex2 = Complex(3.0,5.0)
    println(complex)
    //Ratio size
    println(maxOf(complex,complex2))   // Output the value of / / complex2 (3.0 + 5.0 i)

    //Auto derive double
    val complex3 = Complex2(5.3,6.9)
    val complex4 = Complex2(4,55)

    println(complex3)
    println(complex4)
}

/**To implement the Complex interface, what is specified now is a Double. In fact, it should be better to give it a generic T*/
data class Complex(val a:Double, val b: Double): Comparable<Complex>{
    /**
     * Compares this object with the specified object for order. Returns zero if this object is equal
     * to the specified [other] object, a negative number if it's less than [other], or a positive number
     * if it's greater than [other].
     */
    override fun compareTo(other: Complex): Int {
        return (value() - other.value()).toInt()
    }

    fun value():Double{
        return a*a + b*b
    }
    /**
     * Returns a string representation of the object.
     */
    override fun toString(): String {
        return "($a + $b i)"
    }
}

/**Declaring generics for classes: parameter generics*/
data class Complex2<T>(val a:T, val b: T){
    /**
     * Returns a string representation of the object.
     */
    override fun toString(): String {
        return "($a + $b i)"
    }
}

5, By analyzing kotlin's bytecode, we can see if we can get what generic T is
You can see that after compiling, T becomes Object, which is pseudo generics

6, Take a look at the pseudo generic instances in JAVA and Kotlin

import com.google.gson.Gson
import java.io.File

/**
 * @author:wangdong
 * @description:Java And kotlin's pseudo norm problem
 * reifile Is to make generic parameters concrete
 * reifile Why to define in the inline function
 * Because kotlin and Java are pseudo generics, there will be no T after compilation, so you can only use the inline keyword,
 * (Insert this code into the calling function to know the type of the parameter
 */
fun main(args: Array<String>) {
    val person = Person("wangdong",18)
    Gson().toJson(person).let{
        //Written
        File("person.json").writeText(it)
    }

    //Read
    needAPerson(Gson().fromJson<Person>(File("person.json").readText()))
}

/**
 * Define a class that requires person
 */
fun needAPerson(person: Person){

}

/**
 * See if you can get T
 */
fun <T> testGenerics(){
    //Print out the generics. It's impossible to print. It will report an error
    //Let's see if this T has any
    val t: T? = null
    //println(T::class.simpleName)
}

/**
 * Using the attribute keyword inline of Kotlin to point the generic binding in the method to the caller
 * Keyword to plant code to call point
 */
inline fun <reified T> testGenerics2(){
    println(T::class.java)
}

/**
 * Define an extended method for Gson
 * Implant this code into the call point by dependency
 */
inline fun <reified T> Gson.fromJson(json: String): T = fromJson(json,T::class.java)

/**
 * Define a person class
 */
data class Person(val name: String,val age: Int){

}

7, Well, generics are over here.

Tags: Java JSON less Google

Posted on Sun, 05 Apr 2020 22:00:13 -0700 by danlindley