Difference between Any, Unit and Nothing : Kotlin

This post was originally posted at https://agrawalsuneet.github.io/blogs/difference-between-any-unit-and-nothing-kotlin/ and reposted on Medium on 3rd Mar 2020.

Any

Any is an open class and by default the superclass for all the classes, whether we define it explicitly or not. This is similar to the Object class in Java which is the superclass for each and every class.

/**
* The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass.
*/
public open class Any {

public open operator fun equals(other: Any?): Boolean

public open fun hashCode(): Int
public open fun toString(): String
}
  • equals
  • hashCode
  • toString

equals

/**
* Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
* requirements:
*
* *
Reflexive: for any non-null value `x`, `x.equals(x)` should return true.
* *
Symmetric: for any non-null values `x` and `y`, `x.equals(y)` should return true if and only if `y.equals(x)` returns true.
* *
Transitive: for any non-null values `x`, `y`, and `z`, if `x.equals(y)` returns true and `y.equals(z)` returns true, then `x.equals(z)` should return true.
* *
Consistent: for any non-null values `x` and `y`, multiple invocations of `x.equals(y)` consistently return true or consistently return false, provided no information used in `equals` comparisons on the objects is modified.
* *
Never equal to null: for any non-null value `x`, `x.equals(null)` should return false.
*/
public open operator fun equals(other: Any?): Boolean

hashCode

/**
* Returns a hash code value for the object. The general contract of `hashCode` is:
*
* * Whenever it is invoked on the same object more than once, the `hashCode` method must consistently return the same integer, provided no information used in `equals` comparisons on the object is modified.
* * If two objects are equal according to the `equals()` method, then calling the `hashCode` method on each of the two objects must produce the same integer result.
*/
public open fun hashCode(): Int

toString

/**
* Returns a string representation of the object.
*/
public open fun toString(): String
val any: Any = Any()
any.equals(Any())
any.hashCode()
any.toString()

Unit

Unit class is an object class which means it a singleton class having only one object.

Please continue reading at https://agrawalsuneet.github.io/blogs/difference-between-any-unit-and-nothing-kotlin/

--

--

https://agrawalsuneet.github.io/

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store