https://kotlinlang.org logo
#getting-started
Title
# getting-started
w

Wojciech Rozwadowski

06/07/2022, 1:43 PM
How to create extension function for class implements
invoke
operator? I tried to do this with below function:
Copy code
operator fun <Param, T : Any> ((Param) -> T).invoke(
    param: Param,
    onResult: (Result<T>) -> Unit
) {
    val state = runCatching { this@invoke(param) }
    onResult(state)
}
Above works fine for this function reference:
Copy code
fun test(param: Int): String = "testFunction"
and lambda itself but not for this class:
Copy code
class ClassTest {
    operator fun invoke(param: Int): String = "testClass"
}
Any suggestions?
Copy code
fun main() {
    val testLambda = { param: Int -> "testLambda" }
    val testFunctionReference = ::test
    val testClass = ClassTest()

    testLambda(1) // returns String
    testLambda(1) { onResult: Result<String> ->
        // do sth
    }

    testFunctionReference(1) // returns String
    testFunctionReference(1) { onResult: Result<String> ->
        // do sth
    }

    testClass(1) // returns String
    testClass(1) { onResult: Result<String> ->
        // Too many arguments for public final operator fun invoke(param: Int): String defined in ClassTest
    }
}
r

Ruckus

06/07/2022, 2:38 PM
There's no type of "class that implements invoke". You just need to get a reference to the function:
Copy code
(testClass::invoke)(1) { onResult: Result<String> ->
    // do sth
}
Or you can specify
class ClassTest : (Int) -> String
Copy code
class ClassTest: (Int) -> String {
    override fun invoke(param: Int): String = "testClass"
}

fun main() {
    val testClass = ClassTest()
    testClass(1) // returns String
    testClass(1) { onResult: Result<String> ->
        // do sth
    }
}
👍 1
4 Views