Kotlin function

‮.www‬theitroad.com

In Kotlin, a function is a named block of code that performs a specific task. A function may or may not accept input parameters, and it may or may not return a result.

Here's an example of a simple function in Kotlin:

fun sayHello() {
    println("Hello!")
}

This function is called sayHello, and it does not accept any input parameters or return any value. When the function is called, it simply prints the string "Hello!" to the console.

Here's an example of a function that accepts an input parameter:

fun sayHello(name: String) {
    println("Hello, $name!")
}

This function is also called sayHello, but it accepts a single input parameter of type String called name. When the function is called, it uses the value of name to construct a string that is printed to the console.

Here's an example of a function that returns a value:

fun add(a: Int, b: Int): Int {
    return a + b
}

This function is called add, and it accepts two input parameters of type Int called a and b. When the function is called, it returns the sum of a and b as an Int value.

Here's an example of how to call a function in Kotlin:

fun main() {
    sayHello()
    sayHello("Alice")
    val sum = add(2, 3)
    println(sum)
}

In this example, the program calls the sayHello function twice, once without an input parameter and once with the input parameter "Alice". The program also calls the add function with the input parameters 2 and 3, and stores the result in a variable called sum. Finally, the program prints the value of sum to the console. The output of the program is as follows:

Hello!
Hello, Alice!
5

As you can see, the program called the sayHello function with and without an input parameter, and it called the add function with two input parameters and received a result in return.