Nullpointerexception message

Yes, this is the case where you can safely use !! and I think this is actually the best approach. But why do you care so much about the message if NPE can’t happen in this case?

These messages were very important for Java, because NPE is probably the most common among all exceptions. In Kotlin, it almost never happens (I don’t think I ever got NPE in Kotlin code), so it is really a different story.

1 Like

Well, not every. A while ago, I was working on an app working with a database that had nullable properties. And I needed to filter out nulls, but I needed to do it before I even start doing anything else with that data. So in the end I had this logic:

  1. Connect to the DB and get the objects I need using an existing library.
  2. Collect the results. They are represented using classes from that library, many of them having nullable properties.
  3. Convert the results into internal representation, this time using classes I developed specifically for my app. The relevant properties are not nullable in those classes.
  4. Process the converted results.

Surely, it’s not a generic approach. It worked perfectly because I never needed those nullable properties anywhere in my app. If I needed them nullable in some contexts and non-nullable in others, well, that wouldn’t work so well.

One could also think that having two sets of classes for the same entities is overkill, but it’s not. They are different not only in nullability, but also in that they contain a lot of app-specific logic: some properties are not nullable, some needed to be adjusted/normalized in a specific way, some new calculated properties were added.

Some other apps may have their own specific ways of dealing with nullability without using !!, which is a kind of the last resort brute force option if you don’t have a nice way of dealing with nulls.

Did you consider ?: error("Message is missing")?

Personally I prefer using require, check and error to throwing exceptions explicitly.