fun main() {
print("Hello World!")
}
In this program, main
& println
are two different functions.
Using a function involves two basic steps - Definition & Invocation.
Definition
Definition
Before a function / mini-program is used, it must be defined somewhere. Defining a function involves
- giving it a name
- defining what it’s inputs (or arguments) (no / single / multiple) will be
- defining what it’s output (no / single) will be
- the program / code that instructs the computer to do what the function is intended to do
Syntax for defining a function is :
fun functionName(/* Inputs */): /* Output */ {
/* Code */
}
The function code is enclosed in curly braces {}
.
Example - a function that computes and returns square of the input number can be defined as :
fun square(x: Int) {
return x*x
}
We use the return keyword to return
the output.
Invocation
Invocation
Invocation (or calling a function) means execution of the function, in which its code is read and executed line by line. Syntax for calling a function :
functionName(/* Inputs */)
For example, we can call the println()
function like this :
fun main() {
println("Hello World!") // Prints "Hello World!"
}
The function that returns square of a number can be invoked as :
fun main() {
println(square(5)) // Prints "25"
}
main()
function
main()
function
Below we have defined the main
function which takes no input & returns no output :
fun main() {
print("Hello World!")
}
main
function is the entry point of the program. It’s name should be main
only. We can not run a project without a main
funcntion. Whatever code that we need to execute, has to be written inside this main
function.
You might wonder we have only defined the main
function, but haven’t called it. We don’t have to call the main
function, defining it is enough. The IDE automatically calls it when the project is run.