12

I want to call a overloaded java-function from Kotlin. I want to use a null for parameter that significant to a overload resolution.

How to specify IntArray type for null value?

I don't like a solution with additional varibale of common type.

enter image description here

1
  • 1
    It seems as if the compiler has been improved regarding this constellation... with kotlin 1.3.72 having a variable initialized to null but with appropriate type, now calls the correct function without issues... Commented Jun 22, 2020 at 6:48

1 Answer 1

19

Instead of a variable just cast it, i.e. null as IntArray?, e.g.:

origImg.data.getSamples(0, 0, origImg.width, origImg.height, 0, null as IntArray?) 

Note that this is the same behaviour as in Java, where you also needed to cast null, e.g. (int[]) null, to call the appropriate overloaded method.

You could build a function that gives you a ~typed null (if it doesn't exist yet) with a reified type:

inline fun <reified T>typedNull(): T? = null 

and calling it with:

typedNull<IntArray>() 

But then again, null as IntArray? is clear enough I think and people know it already.

Sign up to request clarification or add additional context in comments.

3 Comments

Good point in underlying the "no difference" behavior compared to plain Java
I've tried null as IntArray and got null cannot be cast to non-null type kotlin.IntArray. Yes, ? is significant. Thanks.
Ah... well, yes... Only types with a ? can hold null values, others not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.