Recognizing this is generally a bad idea… is there...
# getting-started
p
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
@Nonnull
?
c
I mean, something that’s annotated
@Nonnull
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
e
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
p
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
r
Isn't that what mocking and/or faking is for?
i
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
uncheckedNull
will continue to work as it violates the Kotlin type system, see KT-8235 for details.
1