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
- 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.
1234567891011121314151617181920fun validateInput(input: String?) {if (input == null || input.isBlank()) {error("Input cannot be null or blank")}println("Valid input: $input")}fun error(message: String): Nothing {throw IllegalArgumentException(message)}fun main() {validateInput("Hello Kotlin") // This will workvalidateInput("") // This will throw an exception}// OutputValid input: Hello KotlinException in thread "main" java.lang.IllegalArgumentException: Input cannot be null or blank - 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.
123456789101112131415fun printAnyValue(value: Any) {println(value)}fun main() {printAnyValue("Kotlin Guide")printAnyValue(42)printAnyValue(true)}// OutputKotlin Guide42true - 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.
123456789101112fun sayHello(): Unit {println("Hello, Kotlin Guide!")}fun main() {sayHello() // This returns Unit, but you don't need to assign it}// OutputHello, Kotlin Guide!
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.