Chapter 5.1 : Working with Functions in Kotlin (Android)

In this article, you will going to learn about functions and its usage in Kotlin. You’ll also learn function without return value, with return value and default argument.

But before moving to current topic, I explained Kotlin from beginning and you can find full list of previous tutorial at Kotlin page.

Functions

In Java, we called it methods where Kotlin has functions. Functions are very much helpful to distribute your different logic in separate blocks. This way we can create more readable and robust application.

Functions in Kotlin always return a value. So if you don’t specify a return value, it will return Unit.

In Java, we have void which returns nothing similarly Unit in kotlin.

Java Kotlin

Above was very simple example to print "Hello, Chintan". Let’s have a look in some more detailed argument level function in Kotlin. Open Try Kotlin to try online Kotlin compiler.

Return no value

This function will take 2 arguments and print addition.

Note that, we have used Unit at end of Function which means we are not returning any value. Though Unit is optional. You can write above example in below way as well.

Return value

This function will take 2 arguments and return addition.

Default argument

Kotlin supports default argument in functions. If you don’t pass any argument in calling function, it will take default argument.

You can see in example, when we passed only single argument in function, it takes automatically default argument.

Summary

In this article, you learnt how to declare a function. You got knowledge about without returning value, with returning value and default argument in Kotlin.

Thanks for reading. Please ask any doubts in the comment. Don’t forget to share this article.

Protected by Copyscape

Share on Facebook5Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone
  • James Martínez Lara

    You are doing an excellent work.
    Keep it up.

    Thanks a lot!

    • Thank you James for your kind word. I will keep this forward 🙂