Syntax
Kotlin functions are declared using the fun keyword:
fun double(x: Int): Int {
return 2 * x
}
Function parameters are defined using Pascal notation - name: type. Parameters are separated using commas, and each parameter must be explicitly typed:
fun powerOf(number: Int, exponent: Int): Int { /*...*/ }
Function parameters can have default values, which are used when you skip the corresponding argument. This reduces the number of overloads:
fun read(
b: ByteArray,
off: Int = 0,
len: Int = b.size,
) { /*...*/ }
If a default parameter precedes a parameter with no default value, the default value can only be used by calling the function with named arguments:
fun foo(
bar: Int = 0,
baz: Int,
) { /*...*/ }
foo(baz = 1) // The default value bar = 0 is used
When you use named arguments in a function call, you can freely change the order that they are listed in. If you want to use their default values, you can just leave these arguments out altogether.
Consider the reformat() function, which has 4 arguments with default values.
fun reformat(
str: String,
normalizeCase: Boolean = true,
upperCaseFirstLetter: Boolean = true,
divideByCamelHumps: Boolean = false,
wordSeparator: Char = ' ',
) { /*...*/ }
When calling this function, you don't have to name all its arguments:
reformat(
"String!",
false,
upperCaseFirstLetter = false,
divideByCamelHumps = true,
'_'
)
You can skip all the ones with default values:
reformat("This is a long String!")
If a function does not return a useful value, its return type is Unit. Unit is a type with only one value - Unit. This value does not have to be returned explicitly:
fun printHello(name: String?): Unit {
if (name != null)
println("Hello $name")
else
println("Hi there!")
// `return Unit` or `return` is optional
}
When the function body consists of a single expression, the curly braces can be omitted and the body specified after an = symbol:
fun double(x: Int): Int = x * 2
Explicitly declaring the return type is optional when this can be inferred by the compiler:
fun double(x: Int) = x * 2
You can mark a parameter of a function (usually the last one) with the vararg modifier:
fun <T> asList(vararg ts: T): List<T> {
val result = ArrayList<T>()
for (t in ts) // ts is an Array
result.add(t)
return result
}
In this case, you can pass a variable number of arguments to the function:
val list = asList(1, 2, 3)
When you call a vararg-function, you can pass arguments individually, for example asList(1, 2, 3). If you already have an array and want to pass its contents to the function, use the spread operator (prefix the array with *):
val a = arrayOf(1, 2, 3)
val list = asList(-1, 0, *a, 4)
n this article, we will learn infix notation used in Kotlin functions. In Kotlin, a functions marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot.
There are two types of infix function notation in Kotlin-
Standard library infix function notation
fun main(args: Array<String>) {
var a = 15
var b = 12
var c = 11
// call using dot and parenthesis
var result1 =(a > b).and(a > c)
println("Boolean result1 = $result1")
// call using infix notation
var result2 =(a > b) and (a > c)
println("Boolean result1 = $result2")
}
Explanation:
Here, we have called the a.and(b) function using infix (a and b).
Both produce the same result in the standard output.
User defined infix function notation
class math {
// user defined infix member function
infix fun square(n : Int): Int{
val num = n * n
return num
}
}
fun main(args: Array<String>) {
val m = math()
// call using infix notation
val result = m square 3
print("The square of a number is: "+result)
}
The square of a number is: 9
Kotlin functions can be declared at the top level in a file, meaning you do not need to create a class to hold a function. Kotlin functions can also be declared locally as member functions and extension functions.
Kotlin supports local functions, which are functions inside other functions:
fun printArea(width: Int, height: Int): Unit {
fun calculateArea(width: Int, height: Int): Int = width * height
val area = calculateArea(width, height)
println("The area is $area")
}
A member function is a function that is defined inside a class or object:
class Sample {
fun foo() { print("Foo") }
}
Functions can have generic parameters, which are specified using angle brackets before the function name:
fun <T> singletonList(item: T): List<T> { /*...*/ }
Kotlin supports a style of functional programming known as tail recursion. For some algorithms that would normally use loops, you can use a recursive function instead without the risk of stack overflow. When a function is marked with the tailrec modifier and meets the required formal conditions, the compiler optimizes out the recursion, leaving behind a fast and efficient loop based version instead:
Disclaimer: I don't get it actually so just copy pasted the intro here.
Default argument can be apply on parameter of function parameter.
Note: function body has parameters and the value passed to it is called arguments
Function is a block of code which is build to be reused
Unit is new void. which is not necessary to write in the function signature
We can define inline function as below. A function in a single line. remove parenthesis, add "=" operator and just write the statement at the right side of "=".