Functions

35 1 0
                                        

syntax:

fun methodName(name: type): type{

     // statements

}

Above is the syntax of the function. The syntax of kotlin is arrange different compare to other languages like java. 

================

JAVA => int myMethodName(int parameter1, int parameter2){ //block statement; }

KOTLIN => fun myMethodName(parameter1: Int, parameter2: Int): Int { // block statement }

===============

You see in java, the return type int comes before the method name but in kotlin, Int comes after the colon that is after the declaration of parameter. Also, the parameter is arrange backwards. In java, int type is followed by the name of variable. In kotlin, the name of the variable is followed by a colon and then the Int type. Take note also of the int and Int of java and kotlin respectively.

================

fun main(){

     displaySum()

}

fun addingTwoNumbers(param1: Int, param2: Int): Int{

     return param1 + param2

}

fun displaySum(): Unit{

     addingTwoNumbers(10, 20)

}

================

Result:

30

Note: Unit in kotlin means void in java. Also, you can just rewrite the method addingTwoNumbers since kotlin does accept expression since it can inferred the type of the return statement.

==============

fun addingTwoNumbers(param1: Int, param2: Int) = param1 + param2

=============

Note: This is just part of the basic syntax in kotlin website. It is like a summary of the whole documentation that they had but I will keep going until i finish the whole tutorial and that includes the advance.

Kotlin ProgrammingМесто, где живут истории. Откройте их для себя