Functions

It performs a specific task. It can take parameters and return results. It provides reusability of codes.

Create Function: <accessType> <returnType> <functionName>(<parameters>){<codes>}

Function Usage: <functionName>(<parameters>)

Leave blank as we will learn about access types in Classes section.

If our function will return a value, we write data type or object it will return in "<returnType>" section, if it will not return a value, we write "func".

Function names begin with a lowercase letter or "_".

Keywords in A language are used while written codes are compiled into desired software language. Therefore, they cannot be used as function names. It may cause errors if used.

Parameters are separated by ",".

Example:

mainfunc(){

sayHello();

print("2 to power of 3 = {power(2, 3)}");

}


static func sayHello() print("Hello");


static Int powerOf(Int base, Tam power){

Int result=1;

loop(Int n=0; n<power; n++)result*=power;

return result;

}

Output:

Hello

2 to power of 3 = 8

We saw "mainfunc" function in Basic Syntax section. "mainfunc" is static. Static functions only use static objects and functions. That's why we made "sayHi" and "powerOf" functions static. We'll learn more about "static" in Classes section.

Different Parameter Same Name

Functions can have same name with different parameters.

mainfunc(){

sum(1, 2);

sum(4.7d, 3.3d);

}


static func sum(Int n1, Int n2) print("{n1}+{n2}={n1+n2}");


static func sum(Decimal n1, Decimal n2) print("{n1}+{n2}={n1+n2}");

Output:

1+2=3

4.7+3.3=8.0

We've made 2 "add" functions that add whole and decimal numbers.

Scope

Objects can only be accessed in block they were created in.

static Int num1=5;

mainfunc(){

Int num2=10;

print(num1); //5

print(num2); //10

}


static func f(){

print(num1); //5

print(num2); //Error

}

Since variable "number1" is defined in entire class, it can be used anywhere in class. Since variable "number2" is defined in "mainfunc", it can only be used in "mainfunc". It cannot be used in "f" function.