Прежде чем мы узнаем о материализованном,

Обобщения на любом языке — это мощные функции, которые позволяют нам определять классы, методы и свойства, которые доступны с использованием различных типов данных, сохраняя при этом проверку безопасности типов во время компиляции.

This post was originally posted at https://agrawalsuneet.github.io/blogs/reified-kotlin/ and reposted on Medium on 8th Mar 2021.

Лучшим примером дженериков является Array или любая реализация List/Collection.

package kotlin

/**
 * Represents an array (specifically, a Java array when targeting the JVM platform).
 * Array instances can be created using the [arrayOf], [arrayOfNulls] and [emptyArray]
 * standard library functions.
 * See [Kotlin language documentation](https://kotlinlang.org/docs/reference/basic-types.html#arrays)
 * for more information on arrays.
 */
public class Array<T> {
    /**
     * Creates a new array with the specified [size], where each element is calculated by calling the specified
     * [init] function.
     *
     * The function [init] is called for each array element sequentially starting from the first one.
     * It should return the value for an array element given its index.
     */
    public inline constructor(size: Int, init: (Int) -> T)

    /**
     * Returns the array element at the specified [index]. This method can be called using the
     * index operator.
     * ```
     * value = arr[index]
     * ```
     *
     * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException] except in Kotlin/JS
     * where the behavior is unspecified.
     */
    public operator fun get(index: Int): T

    /**
     * Sets the array element at the specified [index] to the specified [value]. This method can
     * be called using the index operator.
     * ```
     * arr[index] = value
     * ```
     *
     * If the [index] is out of bounds of this array, throws an [IndexOutOfBoundsException] except in Kotlin/JS
     * where the behavior is unspecified.
     */
    public operator fun set(index: Int, value: T): Unit

    /**
     * Returns the number of elements in the array.
     */
    public val size: Int

    /**
     * Creates an iterator for iterating over the elements of the array.
     */
    public operator fun iterator(): Iterator<T>
}

Здесь шаблон T может быть любого класса, поэтому мы можем создать Array или List объектов любого класса.

Теперь давайте попробуем получить тип этого шаблона во время выполнения внутри функции.

fun <T> Array<T>.average() : Float {

    print("${T::class.java}") //Compilation Error

    //return default value
    return 0.0f
}

Здесь мы пытаемся добиться того, что мы хотим добавить функцию расширения в массив, которая будет проверять тип во время выполнения, и если этот тип — Int, она вернет среднее значение всех элементов в этом массиве, иначе это вернет 0.0f

Это даст следующую ошибку компиляции

Cannot use 'T' as reified type parameter. Use a class instead.

Возможный способ получить доступ к типу класса Template — передать его в качестве параметра.

Поскольку мы не можем напрямую использовать тип шаблона во время выполнения, здесь нужно использовать reified.

Пожалуйста, продолжайте читать на https://agrawalsuneet.github.io/blogs/reified-kotlin/

Это все на данный момент. Вы можете прочитать другие мои интересные посты здесь или насладиться моими играми или приложениями, перечисленными здесь. Не стесняйтесь использовать мои компоненты Android с открытым исходным кодом в своем приложении, указанном здесь. Или напишите электронное письмо, если вы не нашли то, что ищете, и вам нужна помощь.