Matius Nugroho Aryanto
Matius Nugroho Aryanto

Reputation: 901

Kotlin How to call method that passed as parameter

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?

Upvotes: 2

Views: 217

Answers (1)

Enselic
Enselic

Reputation: 4912

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.

Upvotes: 4

Related Questions