![]() ![]() It is optional to specify Unit as return value. In the next example, we passed the second parameter as well as 4, so it printed 6 (2 + 4)Ī function that does not return any value is actually returning a type called Unit. In first example, we didn't pass the second parameter, so it took the default value of 3 and printed the result as 5 (2 + 3). We have assigned default value 3 to second argument j. In the absence of parameter, Kotlin will use the default value instead. By doing this it becomes optional to pass value for the default parameters. We can assign default value to some arguments of a function in Kotlin. ![]() ![]() We just need to specify the name and pass in the parameters comma separated as shown below. Internally Kotlin will infer the return data type of i + j, and it will automatically return the result.Ĭalling a function is straight forward. In following example, we redefined the function add, but instead of specifying a return type and writing the function body, we just used equals operator and added i and j. Instead of the above syntax, where return type is specified and returned, a function can be inferred. Note that we declared the return type as Int in the function header, as specified by Kotlin syntax we saw earlier. Inside the function we are adding i and j, and we are returning the result using the return keyword. In the following example, we created a function called add. Syntax of function in Kotlin: fun funname(arg1: data type, arg2: data type.): Return data type A Function is a set of executable statements that accomplish an objective.įunction in Kotlin is declared using fun keyword.įun keyword is followed by arguments and statements are written within parenthesis.Īfter arguments a return data type can also be specified.
0 Comments
Leave a Reply. |