Allow naming NPEs

Currently, when using a null thrower -something!! - you get an empty message in the NPE. We suggest to implement the following syntax: something !: "blah blah". That way, we customize our error messages instead of the clumsy something ?: throw NullPointerException("blah blah") or implementing an infix function, something andIfNullThrow "blah blah"

val currentSyntax = listOf(
    { it!! }, // doesn't throw error 
    { it ?: throw NullPointerException("meow"), // clumsy
    { it orThrow "meow" } // using an infix function

val suggestedSyntax = listOf(
    { it!! }, // Add a compiler option to not accept this syntax, similarly to explicitApi()
    { it !: "meow" }, // this is our preferred solution
    { it ?! "meow" } // but we'll also accept this, although it can cause confusion.

What about something ?: error("blah blah")? I would argue it’s concise enough, and without needing to add new syntax to an already-underused feature (NPEs, that is)

1 Like

I would argue that NPEs aren’t underused; The !! operator is used quite a lot in some codebases, especially interop ones.

It is possible, yes; but it doesn’t allow us to completely forbid usage of !! in favor of !:, and is again, clumsy, compared to an “actual” operator.

If you’re willing to accept a bit of ugliness, you can write your own function for it:

infix fun <T> T?.`?!`(errorMessage: String): T = this ?: throw NullPointerException(errorMessage)

val test: String? = "hello"

val test2 = test `?!` "was null"

(Note I wrote this in like 2 minutes, dunno if it works)

1 Like

There is already standard function for this. requireNotNull(it) { "meow" }

1 Like

This would be nice as an extension function but the OP could write such a function themself.

IMO this isn’t a great idea, the !! operator exists to assert that can’t be null, but might come from some interop context, or a smart cast fails so it is still nullable in the type system, if you think something can be null, you should not use !!


I can’t find the YouTrack link at the moment, but the Kotlin team is thinking of improving the automatic message when using !! such that we wouldn’t need to name them ourselves.