Functions
Functions allow you to define a block of code that can be executed multiple times with different inputs. In Kotlin, you
can define functions using the fun
keyword. The syntax for defining a function is as follows:
fun functionName(parameter1: DataType, parameter2: DataType, ...): ReturnType {
// Code to be executed
return value
}
fun
: keyword used to define a functionfunctionName
: name of the function- Parameters (Same syntax as variables)
parameter1
,parameter2
, ...: parameters passed to the functionDataType
: type of the parameters
ReturnType
: type of the value returned by the functionreturn
: keyword used to return a value from the functionvalue
: value to be returned by the function
Example
fun add(a: Int, b: Int): Int {
return a + b
}
val sum = add(5, 3)
println(sum) // Output: 8
In the example above, we define a function add
that takes two parameters a
and b
of type Int
and returns their
sum. We then call the function with arguments 5
and 3
and store the result in a variable sum
. Finally, we print
the value of sum
, which is 8
.
Functions often return a value using the return
keyword, but not all of them do. If a function does not return a
value, it has a return type of Unit
. Unit
is similar to void
in other languages and indicates that the function
does not return anything. Such functions are often used to perform repetitive and common tasks,
such as outputting text with println()
.
Example
fun greet(name: String) { // Return type is Unit, no need to specify
println("Hello, $name!")
}
greet("Alice") // Output: Hello, Alice!
In the example above, we define a function greet
that takes a parameter name
of type String
and prints a greeting
message. The return type of the function is Unit
, which is not explicitly specified.
For the sake of conciseness, Unit
is almost always omitted as a return type.
You can also define functions with default values for parameters. This allows you to call the function without providing values for all parameters. If you do not provide a value for a parameter with a default value, the default value will be used.
Example
fun greet(name: String = "World") {
println("Hello, $name!")
}
greet() // Output: Hello, World!
greet("Alice") // Output: Hello, Alice!
In the example above, we define a function greet
that takes a parameter name
of type String
with a default value
of
"World"
. We then call the function without providing a value for name
, which uses the default value. We also call
the
function with the argument "Alice"
, which overrides the default value.
If you have multiple parameters, the ones with default values must come after the ones without default values. You can also use named arguments to specify the values for parameters with default values.
Example
fun greet(greeting: String = "Hello", name: String = "World") {
println("$greeting, $name!")
}
greet() // Output: Hello, World!
greet("Hi") // Output: Hi, World!
greet("Hi", "Alice") // Output: Hi, Alice!
greet(name = "Bob") // Output: Hello, Bob!
In the example above, we define a function greet
with two parameters greeting
and name
, both of type String
,
with default values of "Hello"
and "World"
, respectively. We then call the function with different combinations of
arguments and named arguments to see how the default values are used.
Functions can also be defined as expressions using the =
operator. This allows you to define functions concisely
without using curly braces and the return
keyword.
Example
fun add(a: Int, b: Int) = a + b
val sum = add(5, 3)
println(sum) // Output: 8
In the example above, we define a function add
that takes two parameters a
and b
of type Int
and returns their
sum. The function is defined as an expression using the =
operator, which automatically returns the result of the
expression.
The main
Function
In Kotlin, the main
function is the entry point of a Kotlin program. When you run a Kotlin program, the code inside
the
main
function is executed. The main
function is defined as follows:
fun main() {
// Code to be executed
}
When you run a Kotlin program, the code inside the main
function is executed sequentially. You can define other
functions and call them from the main
function to organize your code.
Lambdas
Lambda expressions (also known as anonymous functions) are a concise way to define functions that can be passed as arguments to other functions. In Kotlin, functions are first-class citizens, which means they can be treated like any other value. This allows you to pass functions as arguments, return functions from other functions, and store functions in variables.
Lambda Syntax
Lambda expressions are defined using curly braces {}
and the ->
operator. The syntax for a lambda expression is as
follows:
{ parameter1: DataType, parameter2: DataType, ... ->
// Code to be executed
}
{}
: curly braces used to define a lambda expressionparameter1
,parameter2
, ...: parameters passed to the lambda expressionDataType
: type of the parameters->
: operator used to separate parameters from the code block// Code to be executed
: code block to be executed by the lambda expression- The last expression in the lambda block is the return value
These lambda expressions can be assigned to variables and passed as arguments to other functions, which allows you to write more concise and expressive code.
Example
val add: (Int, Int) -> Int = { a, b -> a + b }
val multiply: (Int, Int) -> Int = { a, b -> a * b }
fun calculate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
In the example above, we define two lambda expressions add
and multiply
that take two parameters a
and b
of type
Int
and return their sum and product, respectively. We then define a function calculate
that takes two parameters
a
and b
of type Int
and an operation that is a lambda expression (Int, Int) -> Int
. The calculate
function
calls the operation with the given parameters a
and b
and returns the result.
You can input any lambda expression that matches the (Int, Int) -> Int
signature into the calculate
function, which
allows you to perform different operations on the input values.
A function like calculate
that takes another function as an argument is known as a higher-order function. Higher-order
functions are a powerful feature of Kotlin that allows you to write more flexible and reusable code.