Is it a good practice to use Nothing in generics?

Viewed 1287

Like in this example:

sealed class Option<T>

object None : Option<Nothing>() // <-- like this

class Some<T> : Option<T>()

Or, if it's not a good practice, what should I use here instead?

Are there any official response/article on that? Or is there any argumentation that this is a good practice?

I know that Nothing was designed to be used as a type for return value for functions that never returns any value, so I'm not sure if using it as a generic parameter is a valid use.

I know there is an article that says that you can do that, but I'm not sure if I can trust it.

And the author of koptional uses it too, but I don't know if I can trust that either.

Also, it looks like in Scala Option is implemented similar to that, None have type Option[Nothing] and Scala's Nothing is similar to Kotlin's Nothing.

1 Answers

I agree with @zsmb13's comment. Using Nothing in a generic type hierarchy is perfectly valid and even gives benefits over other options:

  • First, Nothing is embedded in the Kotlin type system as a subtype of any other type, so it plays well with generics variance. For example, Option<Nothing> can be passed where Option<out Foo> is expected.

  • Second, the compiler will perform control flow checks and detect unreachable code after a Nothing-returning member call when the type is statically known.

See also: A Whirlwind Tour of the Kotlin Type Hierarchy

Related