1

The following line of code is throwing a compile error related to Renderer::onScoreChange. The reported error is: Type mismatch. Required:(Int, Int) → Unit Found: KFunction3<Renderer, @ParameterName Int, @ParameterName Int, Unit>

var score by EngineObserver<Int>(20, Renderer::onScoreChange)

I'm trying to pass a function reference to a custom Delegate extending from the ObservableProperty class but not sure why its not recognizing the passed member function as satisfying the requirements of the function argument. Thoughts from anyone?

class EngineObserver<T>(
   initialValue: T, 
   val notify : (oldVal : T, newVal : T) -> Unit
) : ObservableProperty<T>(initialValue) {
   override fun afterChange(property: KProperty<*>, 
                            oldValue: T, 
                            newValue: T) {
        super.afterChange(property, oldValue, newValue)
        notify(oldValue, newValue)
   }
}

class Renderer {
   fun onScoreChange(oldVal : Int, newVal : Int){
      println("Score changed from $oldVal to $newVal")
   }
}

2 Answers 2

1

Renderer::onScoreChange is a member function which has Renderer as its first parameter. You probably need a function reference applied to a certain instance: renderer::onScoreChange

Sign up to request clarification or add additional context in comments.

1 Comment

Passing an instance, not the class itself, solved the issue.
0

Miha_x64 is right. To make your code work, you have to do the following:

class Renderer {
    companion object {
        fun onScoreChange(oldVal: Int, newVal: Int) {
            println("Score changed from $oldVal to $newVal")
        }
    }
}

var score by EngineObserver<Int>(20, Renderer.Companion::onScoreChange)

Alternatively, if you have a Renderer instance you want to call that method on, you can do:

val renderer = Renderer()
var score by EngineObserver<Int>(20, renderer::onScoreChange)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.