Table of content

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 similar to java.Lang.Object
  • Up-casting occurs automatically when you provide lower types 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>){
									methodReturnsUnit()
								}								
								fun methodReturnsUnit() {
									println("This block has no explicit return type, so returns Unit")
								}
								

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

Not 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 return type as Nothing when it wants to return Nothing type, if it doesn't mention then return type would considered as Unit.


								fun throwError(): Nothing {
									throw RuntimeException()
								}
								
								// running infinite loops
								fun infyLoop(): Nothing {
									while(true){
										println("this is infinite loop")
									}
								}
								
								fun main(args:Array<String>)
								{
									infyLoop();
								}
								

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
								{
									while(true){
										println("this is infinite loop")
									}
								}
								

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

Unit Functions in Kotlin

About Author

This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions