2

in javasript, if we know the name of the method, we can pass it as parameter and call it like this

function foo(methodName){
	methodName()
}

function doSomething(){
	console.log("DO Something")
}
foo(doSomething)

I want to do something like this in kotlin, consider i have a class like this

Class DataModel{}
Class Foo (){
    fun build(data:DataModel,val onThis:AnyMethod){
        if(data.size>0){
            val param = somevalue
            onThis(param)
        }
    }
}

then in my Activity for example i have doThis method

class MainActivity : AppCompatActivity(){
    //rest of code
    fun doThis(param:Int){
        Log.e("DO","THIS ${param}")
    }
}

in my OnCreateView i want to call something like this

val a= new Foo()
a.build(data, doThis)

To do this, how my Foo Class should be?

1 Answer 1

4

Change val onThis:AnyMethod to onThis: (Int) -> Unit, i.e. like this:

class Foo {
    fun build(data: DataModel, onThis: (Int) -> Unit) {
        if (data.size > 0) {
            val param = somevalue
            onThis(param)
        }
    }
}

Then you can do like this

// val mainActivity: MainActivity = ...

val a = Foo()
a.build(data, mainActivity::doThis)

or, if you run that code from within a member function of MainActivity:

val a = Foo()
a.build(data, ::doThis)

More information on how to pass around lambdas/functions/member functions can be found in the official documentation.

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

2 Comments

I have edited my question since i found new problem, what if the function needs parameter?
@MatiusNugrohoAryanto Then you change from () -> Unit to (Int) -> Unit.

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.