Search code examples
reflectionkotlinkotlin-reflect

Kotlin check if function requires instance parameter


If a KCallable is created using Any()::toString then when it's later referenced you don't need to pass that Any instance (when using call).

Though if it's created using Any::toString (not an instance of Any) it's required to pass an Any instance.

So my question is how can I easily find out whether I need to pass that instance parameter and is this parameter mandatory?

I found a way to do this:

callable.parameters[0].kind == KParameter.Kind.INSTANCE

but it isn't quite nice and I wonder if there's an easier or recommended way to solve this. Thanks!


Solution

  • An improvement of the method you suggested is to check the instanceParameter property: if it is not null, then the callable expects an instance:

    val isInstanceCallable = callable.instanceParameter != null
    

    Also, extension functions like fun Any.foo() = ... will have null in the instanceParameter, and you likely want to check the extensionReceiverParameter as well.


    Also, if you only need to work with callable references, you can check whether they have a bound receiver (i.e. the instance that it is bound to). Use the boundReceiver property:

    val instance = (callable as CallableReference).boundReceiver
    

    When a callable reference is unbound, it will return a special value CallableReference.NO_RECEIVER, therefore you just need to compare the returned value with it:

    val bound = (callable as CallableReference).boundReceiver != CallableReference.NO_RECEIVER
    

    (runnable example)