This post explains the basics of implementing functions in the Kotlin programming language.
Functions in Kotlin are declared by using the fun keyword. Here is a simple Hello Kotlin function.
fun sayHello()
{
print("Hello Kotlin")
}
fun is the keyword that defines the function, sayHello is the name of the function. The body of the function is enclosed between the two curly braces.
The following code will execute the function and get the output.
fun main(args: Array<String>)
{
sayHello()
}
fun sayHello()
{
print("Hello Kotlin")
}
Kotlin function parameters require compulsory type declaration. Here is a function that adds two numbers and prints the sum.
fun main(args: Array<String>)
{
addTwoNumbers(1,2)
}
fun addTwoNumbers(a :Int,b:Int)
{
print(a+b)
}
fun main(args: Array<String>)
{
addTwoNumbers(2)
}
fun addTwoNumbers(a :Int ,b:Int=1,)
{
var sum:Int =a+b
print("$a + $b = $sum")
}
Kotlin supports named parameters
fun main(args: Array<String>)
{
addTwoNumbers(a=4,b=3)
}
fun addTwoNumbers(a :Int ,b:Int=1,)
{
var sum:Int =a+b
print("$a + $b = $sum")
}
Kotlin supports variable numbers of parameters with the varargs keyword.
fun main(args: Array<String>)
{
addManyNumbers(1,2,3,4)
}
fun addManyNumbers(vararg integers:Int)
{
var sum:Int =0
var x:Int
for(x in integers)
sum=sum +x
println(sum)
}
Kotlin supports one line functions
fun main(args: Array<String>)
{
println( 1 double 2)
println( 6.double(2))
}
infix fun Int.double(x: Int): Int { return 2 *x}
We will deal with lambdas in the next post.
End
0 Comments