Wojciech Rozwadowski
06/07/2022, 1:43 PMinvoke
operator? I tried to do this with below function:
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:
fun test(param: Int): String = "testFunction"
and lambda itself but not for this class:
class ClassTest {
operator fun invoke(param: Int): String = "testClass"
}
Any suggestions?
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
}
}
Ruckus
06/07/2022, 2:38 PM(testClass::invoke)(1) { onResult: Result<String> ->
// do sth
}
Ruckus
06/07/2022, 2:39 PMclass ClassTest : (Int) -> String
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
}
}