Is it possible to call a function by reflection inside other function

    fun <T> ArrayList<T>.filterOnCondition(condition: (T) -> Boolean): ArrayList<T> {
    val result = arrayListOf<T>()
    
    for (item in this){

        /*if (condition(item)){
            result.add(item)
        }*/

        /*if(::isMultipleOf(item, 5)){
            result.add(item)
        }*/

        if(::checkCondition()){
            result.add(item)
        }
    }

    return result
}

fun isMultipleOf (number: Int, multipleOf : Int): Boolean = number % multipleOf == 0

fun checkCondition (): Boolean {
    //some condition
   return true
}

fun main(args: Array<String>) {
    var resultList = list.filterOnCondition { isMultipleOf(it, 5) }
}

but the calling of method ‘checkCondition’ gives an error as below.
“This syntax is reserved for future use; to call a reference, enclose it in parentheses: (foo::bar) (args)”

I know I can call this method directly by removing the reflection call( :: ) and this will work fine but can I use reflection here?
I tried to understand the concept of reflection from Kotlin docs for my case but no luck.

If you want to call a function using reflection (not that I know why you would) you can use those 2 methods

::function.call(args...)
(::function)(args...)

For both versions the return value is type checked. But only the second version is typesafe for the arguments.
If you want to pass a function as an argument to a higher order function you have a few options.
You can create a anonymous functions like this

call(fun() {println("hi")})

or use a lambda as you did in your main function. The third option is to pass a reference to a function

call(::someFunction)
1 Like