# getting-started

Paul Griffith

09/28/2022, 5:20 PM
Recognizing this is generally a bad idea… is there any way to force the compiler to allow me to pass a null value into a Java method with a parameter annotated as

Casey Brooks

09/28/2022, 5:55 PM
I mean, something that’s annotated
is basically declaring that it will throw an NPE if that variable is null. So you could just use
on what you’re passing in and get that same exception from Kotlin before passing it into the Java code, I guess. You could also try casting the nullable Kotlin type into the non-null type. Since there’s no runtime distinction between the two types, and you’re passing the variable directly into a Java method, it might work


09/28/2022, 5:57 PM
I interpreted this as a Java method being incorrectly annotated as nonnull
Copy code
fun <T> uncheckedNull(): T = null as T
as a hack, I think you can use this as an argument and Kotlin won't (currently) check it

Paul Griffith

09/28/2022, 6:03 PM
Ah, that does indeed work in this case. Neat!
For context, this was a case where Nonnull was a valid annotation, but I still “knew better” than the compiler (I know that none of the possible NPEs can be thrown, because this is just a unit test where I need to pass a constructed object, but it won’t actually be used)
Mocking is probably the better answer, and what I switched to, but I was mostly curious if I could trick the compiler in any way


09/28/2022, 6:18 PM
Isn't that what mocking and/or faking is for?


09/30/2022, 12:00 PM
You can create a helper java method without annotations that calls that java method. It is better because it's not guaranteed that the hack with
will continue to work as it violates the Kotlin type system, see KT-8235 for details.