Jump to content

Draft:Covariant Nothing Object

From Wikipedia, the free encyclopedia

Covariant Nothing Object is a pattern used in programming languages like Kotlin or Scala. It allows turning immutable generic classes into singleton objects thanks to usage of covariant type modifier and a bottom type (Nothing type in Kotlin).

The most notable example is an empty list in Kotlin. List interface in Kotlin represents a read-only type, and whose type parameter has covariant type modifier, so functions like emptyList() or listOf(), that are the standard way to create an instance of an empty list, always return exactly the same object, that is implemented as a subtype of List<Nothing>. Since Nothing is a bottom type (a subtype of all types), List<Nothing> is a subtype of all lists.

This pattern was first described by Marcin Moskała in the Advanced Kotlin book[1].

References

[edit]
  1. ^ Moskała, Marcin (2023). Advanced Kotlin (1 ed.). Poland: Kt. Academy. pp. 20–27. ISBN 978-8396684745.{{cite book}}: CS1 maint: date and year (link)