Search code examples
functionkotlinmethodsreturn

Reassigning function body in Kotlin


I need to change return function ( modify() method) in accordance with the object provided to the constructor. I see two ways to do it:
Via function body reassign:

class Modifier<T>{
    lateinit var func: ()->T

    constructor(sendable: Sendable<T>){
        func = {  sendable.send() }
    }
    constructor(modifier: Modifier<T>){
        func = {  modifier.modify() }
    }
    fun modify():T{
        return func()
    }
}

and through intermediate variable:

class Modifier<T>{
    var result:T

    constructor(sendable: Sendable<T>){
        result = sendable.send()
    }
    constructor(modifier: Modifier<T>){
        result = modifier.modify()
    }
    fun modify():T{
        return result
    }
}

But I have some doubts if it is implemented in the correct way. Please give your opinoin how it is effective from the point of view of resource consumption and overall realization. Thanks.

to have the most effective way of switching returning value in conditions of the huge calculation amount (recursion) saving both processing and memory capabilities.


Solution

  • The first of your two options is the only one that does what you describe in the comments, that you want the value recalculated every time modify() is called. You have to store the function reference to be able to call it repeatedly. The function reference will capture a reference to your Sendable or Modifier instance, so it will stay in memory even if not referenced elsewhere outside this class.

    (By the way, lateinit is unnecessary for a property that is initialized in every constructor or in an init block.)

    You can shorten your syntax as follows. It seems a little weird to define a lambda to do nothing but call a single function so this syntax is a little more idiomatic, although there isn't a firm convention on this. The compiler will treat it the same.

    class Modifier<T>{
        var func: ()->T
    
        constructor(sendable: Sendable<T>){
            func = sendable::send
        }
        constructor(modifier: Modifier<T>){
            func = modifier::modify
        }
        fun modify():T{
            return func()
        }
    }