How to write my own by extension function

J_Strauton :

I have a default function like this:

fun <T> makeDefault(): Animal<T> = Animal<Nothing>(
    name = "",
    size = 0,
    age = 0
)

I saw that there is the by operator, which can be used for view models like this:

val model: MyViewModel by viewModels() 

Question: How I can create a function that behaves like that for my makeDefault()?

What I want to do:

val animal: Animal<Dog> by makeDefault()
S-Sh :

You can create your own Delegate, not extension:

import kotlin.reflect.KProperty

class DefaultDelegate<T> {
    private var created: Animal<T> = Animal<Nothing>(
            name = "",
            size = 0,
            age = 0
        )

    operator fun getValue(thisRef: Any?, property: KProperty<*>): Animal<T> {
        return created
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Animal<T>) {
        created = value
    }
}

Then use it:

val animal: Animal<Dog> by DefaultDelegate()

For more information, see Delegated properties doc

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=397773&siteId=1