Monday 29 January 2018

Kotlin: unit (or) void functions

Unit returning functions are similar to void functions in Java. If a function do not return any value, its return type is Unit.

UnitDemo.kt
fun welcome(name: String) : Unit {
 println("Welcome $name")
 
 return Unit // You can simply call return
}

fun main(args: Array<String>) {
 var returnValue = welcome("Hari krishna")
 println("Returned value is $returnValue")
}


Output
Welcome Hari krishna
Returned value is kotlin.Unit

Specifying the type ‘Unit’  and returning Unit from unit functions is optional.


UnitDemo.kt
fun welcome(name: String) {
 println("Welcome $name")
}

fun main(args: Array<String>) {
 var returnValue = welcome("Hari krishna")
 println("Returned value is $returnValue")
}


Previous                                                 Next                                                 Home

No comments:

Post a Comment