Search code examples
androidkotlinextension-function

How to write my own by extension function


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()

Solution

  • 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