class X {
fun someFunc(x: Int, y: String, z: Double) {
println("x = [$x], y = [$y], z = [$z]")
}
}
fun main(args: Array<String>) {
val func = X::someFunc
val instance = X()
func.call(instance, 1, "Hi", 123.45)
}
Given the code above how can I convert it to a function with instance built-in so when calling I can just pass the params without instance
? (I could just use X()::someFunc
but that's not the point of this question)
You could just implement a delegate wrapping that logic. Example implementation:
class KCallableWithInstance<out T>(private val func: KCallable<T>, private val instance: Any) : KCallable<T> by func {
private val instanceParam = func.instanceParameter ?:
func.extensionReceiverParameter ?:
throw IllegalArgumentException("Given function must not have a instance already bound")
init {
val instanceParamType = instanceParam.type.jvmErasure
if (!instance::class.isSubclassOf(instanceParamType))
throw IllegalArgumentException(
"Provided instance (${instance::class.qualifiedName}) isn't an subclass of " +
"instance param's value's class (${instanceParamType::class.qualifiedName})")
}
override fun call(vararg args: Any?): T
= func.call(instance, *args)
override fun callBy(args: Map<KParameter, Any?>): T
= func.callBy(args + (instanceParam to instance))
override val parameters = func.parameters.filter { it != instanceParam }
}
fun <T> KCallable<T>.withInstance(instance: Any): KCallable<T>
= KCallableWithInstance(this, instance)
And then use it like this (example based on the code in question): func.withInstance(instance).call(1, "Hi", 123.45)
You could also create a Pair
which maps the instance to the KFunction
. Then you define an extension function call
on that Pair
like this:
// class X as defined in the question
fun <S: Any, T: Any> Pair<S, KFunction<T>>.call(vararg args: Any?): T {
val (instance, func) = this
return func.call(instance, *args)
}
fun main() {
val func = X::someFunc
val instance = X()
val funcInstancePair = instance to func
funcInstancePair.call(1, "Hi", 123.45)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With