Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Functions


Functions in Kotlin are blocks of code that perform a specific task. They help in organizing code, making it reusable, and easier to understand. Here's a simple explanation with an example:

Declaring Functions

You can declare a function using the fun keyword followed by the function name and its parameters (if any).

Example

fun greet() {
println("Hello, Kotlin!")
}

Calling Functions

To execute a function, you simply call its name followed by parentheses ().

Example

fun main() {
greet() // Calling the greet function
}

Parameters and Return Types

You can define parameters inside the parentheses of a function to accept input values. Similarly, you can specify a return type to return a value from a function.

Example

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

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

Calling Functions with Parameters

When calling a function with parameters, you pass values inside the parentheses.

Example

fun main() {
greet("Alice") // Output: Hello, Alice!

val sum = add(5, 3)
println("Sum: $sum") // Output: Sum: 8
}

Default Parameters

You can provide default values for function parameters, making them optional.

Example

fun greet(name: String = "World") {
println("Hello, $name!")
}

Named Arguments

You can specify function arguments by name, regardless of their order.

Example

fun greet(greeting: String, name: String) {
println("$greeting, $name!")
}

fun main() {
greet(name = "Alice", greeting = "Hi") // Output: Hi, Alice!
}

Single-Expression Functions

For short functions, you can use a single expression without curly braces {}.

Example

fun square(x: Int): Int = x * x

Conclusion

Functions are essential building blocks in Kotlin that allow you to encapsulate logic, accept inputs, and return outputs. By defining and calling functions, you can modularize your code and make it more organized and readable.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java