

This is just the brief introduction to functions in Kotlin.As mentioned in the picture above, a class has following three parts : In the above example, you can replaceįun getName(firstName: String, lastName: String): String = "$firstName $lastName"įun getName(firstName: String, lastName: String) = "$firstName $lastName" It is optional to explicitly declare the return type in such case because the return type can be inferred by the compiler. The codes inside curly braces of the function body and specify the body after = symbol if the function returns a single expression (like above example). You will learn about arguments later in this article. It means, this function doesn't accept any argument. In the above program, the parenthesis ( ) is empty. Here, the name of the function is callMe. Then comes the name of the function ( identifier). To define a function in Kotlin, fun keyword is used. Here's how you can define a function in Kotlin: How to create a user-defined function in Kotlin?īefore you can use (call) a function, you need to define it. Such functions are called user-defined functions. Here is a link to the Kotlin Standard Library for you to explore.Īs mentioned, you can create functions yourself. When you run the program, the output will be: Result = 2.345207879911715

sqrt() returns square root of a number ( Double value).print() is a library function that prints message to the standard output stream (monitor).The standard library functions are built-in functions in Kotlin that are readily available for use. You can create two functions to solve this problem:ĭividing a complex program into smaller components makes our program more organized and manageable.įurthermore, it avoids repetition and makes code reusable.ĭepending on whether a function is defined by the user, or available in standard library, there are two types of functions: For example, you need to create and color a circle based on input from the user. In programming, function is a group of related statements that perform a specific task.įunctions are used to break a large program into smaller and modular chunks.
