How to make functions in Kotlin -1 ?

 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")
}


Varanasi Software Junction:Kotlin Function

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)
}


Varanasi Software Junction:Kotlin Function

trailing commas are allowed in function parameter declarations.

fun main(args: Array<String>)
{
    addTwoNumbers(1,2)
}
fun addTwoNumbers(a :Int,b:Int,)
{
    print(a+b)
}


Default value parameters are allowed in Kotlin starting from the right.
fun main(args: Array<String>)
{
    addTwoNumbers(2)
}
fun addTwoNumbers(a :Int ,b:Int=1,)
{
   var sum:Int =a+b
    print("$a + $b = $sum")
}

Varanasi Software Junction:Kotlin Function

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")
}

Varanasi Software Junction:Kotlin Function

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)

}


Varanasi Software Junction:Kotlin Function

Kotlin supports one line functions
fun main(args: Array<String>)
{
   print( addTwoNumbers(1,2))
}
fun addTwoNumbers(a:Int ,b:Int )=a+b

Varanasi Software Junction:Kotlin Function




Infix function will always be added to a class. in this case Int

fun main(args: Array<String>)
{
   println( 1 double  2)


   println( 6.double(2))
}
infix fun Int.double(x: Int): Int { return 2 *x}






Varanasi Software Junction:Kotlin Function

We will deal with lambdas in the next post.









End

Post a Comment

0 Comments