Special Data Types in Kotlin: Nothing, Any, & Unit Explained

In Kotlin besides main data types are few data types available which is used to handle special cases. These data types are called Special Data Types in Kotlin. The names of these data types are Nothing, Any, and Unit. These perform a crucial role in defining functions and handling exceptions including type safety in Kotlin. After learning about them, you can write more optimized and error-resistant code.

Special Data Types in Kotlin: Nothing, Any, & Unit Explained

Special Data Types in Kotlin: Nothing, Any, & Unit Explained

  1. Nothing: Nothing is a type with no values. Functions with nothing never return a value because it throw an exception or it could enter into an infinite loop. It defines that the function will not execute like normal functions. It is used in these functions where we terminate the program by logging errors and throwing exceptions or infinite loops.
  2. Any: Any is a supertype of all non-nullable types in Kotlin. We have all learned about Object type in Java, Any is similar to that in Kotlin. Almost every class in Kotlin inherited Any. Function with any can accept any data type value whether it’s String, Int, or Boolean. But we have to make sure that type is non-nullable.
  3. Unit: A unit with functions in Kotin is used when a function does not return a meaningful value. It is similar to Void in Java. Functions that do not return any value will return Unit in Kotlin.

I have tried my best to explain special data types in Kotlin with the simplest example. If you want to make more coding examples regarding these please let me know in the comment section. Until then Happy Coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *