Any and Any?

Any is a data type in kotlin, any type is super-type of all non-nullable types in kotlin. Any type can include below:

  • This includes basic types such as Int, Float, and others
  • any type cannot hold null values in kotlin
  • This is similar to java.Lang.Object
  • Up-casting occurs automatically when you provide lower types of values to Any data type
  • var:Any =10
  • You can handle the null values along with the other value by using a question mark at the end of Any like Any?

Type inference in Kotlin

Unit Type in Kotlin

Functions always return a value, Functions that don't actually return anything in kotlin will return Unit, a type that has a single value, also called Unit.

Kotlin does not have void functions, like Java and C. So kotlin enjoys with Unit value

Most of the time you don't need to explicitly specify Unit as a return type or return Unit from functions.

If you write a function with a block body and do not specify the return type, the compiler will treat it as a Unit function.

Unit means nothing but only one instance

fun main(args:Array<String>){
fun methodReturnsUnit() {
	println("This block has no explicit return type, so returns Unit")

In the above program, we have two functions, methodReturnsUnit returns no explicit type, so it returns Unit. In Kotlin main function returns Unit

Null Assertion [!!]

Nothing in Kotlin

In Simple terms, Nothing is a return type of a function, function return this Nothing Type, when the execution of function may or may not reach the bottom of the Function.

Functions return Nothing when it explicitly throws an Exception or when the function has infinite loops.

Functions must specify the return type as Nothing when it wants to return Nothing type if it doesn't mention then the return type would be considered as Unit.

fun throwError(): Nothing {
	throw RuntimeException()

// running infinite loops
fun infyLoop(): Nothing {
		println("this is infinite loop")

fun main(args:Array<String>)

The main method cannot be returning any value other than Unit, but I tried it with nothing and got below error.

fun main(args:Array<String>):Nothing
		println("this is infinite loop")

Error running 'FirstKotlinUsageKt': Top-level function 'main' not found in package ' '

Unit Functions in Kotlin

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Subscribe to See Videos

Subscribe to my Youtube channel for new videos : Subscribe Now