Alubar
Alubar

Reputation: 31

How to invoke a kotlin function when given the function name as a string?

I'm making a project with many functions, each named prx, x being a number up to 200, is it possible to create a call from a string like this

var ="pr" + x

Upvotes: 3

Views: 1606

Answers (1)

mightyWOZ
mightyWOZ

Reputation: 8315

You can do this using reflection

class MyTestClass {
    fun pr1(): Int = 5
    fun pr2(value: Int) = value.toString()
}


class SomeOtherClass{
    fun main(){

        val myTestClassObj = MyTestClass()
        // Find pr1 by name (function without arguments)
        val pr1 = myTestClassObj::class.java.getMethod("pr1").kotlinFunction

        // call pr1, pass class object as argument, used to call the function
        val pr1Result = pr1?.call(myTestClassObj)

        // Find function with arguments, pass function name and type of arguments
        val pr2 = MyTestClass::class.java.getMethod("pr2", Int::class.java).kotlinFunction

        // Call pr2, pass class reference and the function parameter
        val pr2Result = pr2?.call(myTestClassObj, 100)

    }
}

Be carefull when working with reflection, its easy to create untraceable bugs using it and often it is only a workaround for bad design.

Upvotes: 4

Related Questions