Как ожидается использование типа R generi c в ReadWriteProperty? - PullRequest
0 голосов
/ 09 апреля 2020

Как ожидается использование типа R generi c? Везде, где я вижу реализацию ReadWriteProperty, R определяется как Any или Any?, и тогда две части реализации, использующие тип R (ниже именуемый thisRef), никогда не используются.

Kotlin ReadWriteProperty определяется следующим образом (код был скопирован / вставлен из исходного файла):

/**
 * Base interface that can be used for implementing property delegates of read-write properties.
 *
 * This is provided only for convenience; you don't have to extend this interface
 * as long as your property delegate has methods with the same signatures.
 *
 * @param R the type of object which owns the delegated property.
 * @param T the type of the property value.
 */
public interface ReadWriteProperty<in R, T> {
    /**
     * Returns the value of the property for the given object.
     * @param thisRef the object for which the value is requested.
     * @param property the metadata for the property.
     * @return the property value.
     */
    public operator fun getValue(thisRef: R, property: KProperty<*>): T

    /**
     * Sets the value of the property for the given object.
     * @param thisRef the object for which the value is requested.
     * @param property the metadata for the property.
     * @param value the value to set.
     */
    public operator fun setValue(thisRef: R, property: KProperty<*>, value: T)
}

1 Ответ

1 голос
/ 09 апреля 2020

Вы можете создать свойство делегата, предназначенное для определенного типа получателя c. Он может быть использован только внутри этого класса и его подклассов, но у вас будет доступ к его функциям и свойствам.

Например, вы можете создать класс, который подсчитывает вызовы любых его свойств, использующих делегат. :

open class Ticker {
    var ticks = 0
        private set

    class CountedAccess<T> (private val value: T) : ReadOnlyProperty<Ticker, T> {
        override fun getValue(thisRef: Ticker, property: KProperty<*>): T {
            thisRef.ticks++
            return value
        }
    }
}

Тогда подкласс будет отслеживать количество вызовов к любому из своих делегированных свойств:

fun main() {
    class Something: Ticker() {
        val foos by CountedAccess(5)
        val bar by CountedAccess("Hello, world!")
    }

    val something = Something().apply {
        repeat(Random.nextInt(3)) {
            println("Number of foos is $foos")
            repeat(Random.nextInt(3)) {
                println("Bar says $bar")
            }
        }
    }
    println("Something's properties were accessed ${something.ticks} times.")
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...