Never nullable type

What if someone wants a type to never be nullable.
It already have its own domain null value.

Something like java’s Optional which is just confusing and error-prone when used as nullable instead of some kind of TriState.

How would you address this?

Some kind of compile-time check maybe?

You just don’t use nullable Optional as a matter of style. Even nullable Boolean is usually a bad style, since it is confusing. If you are really worried that somebody else accidentally introduces it in your codebase and you don’t have a code review process to catch it, then you can probably add some kind of a lint/inspection to catch it.

1 Like

I do not completely agree about nullable boolean. There are cases (especially in UI), when you want to use null as a fallback to default value. In this case nullable Boolean is quite useful and means “default”.

In scenarios like this sometimes it’s better to use 3-valued enum instead. You call it a Null object pattern:

enum class BooleanAnswer {

This way you avoid using plain nulls and you instead have a “null” value with a concrete business conotation.

Again, I do not agree. In Roman’s own article, null is proposed as a good treatment for the absense of value. And the case I meant is exactly about that. Moreover thinks like val actual = value ?: defaultValue looks idiomatic. Instead of

val actual = when(answer){
  YES -> true
  NO -> false
  NOT_ANSWERED -> defaultValue
1 Like

‘Absence of value’ could have many subtly-different meanings. For example: uninitialised; unknown; unchanged; invalid; unused; unrestricted; unavailable; inapplicable.

(That’s not a problem, as long as you make sure it’s clear which meaning applies in each case. And if you need to use and distinguish two or more of those meanings, then of course you’ll need some other mechanism.)