Introduction
In the previous chapter, you created your first Kotlin program which prints "Hello, Kotlin!" to the console. In this chapter, we will break down the structure of this simple program to understand the basic components and syntax of a Kotlin program.
Hello World Program
Here is the "Hello, Kotlin!" program you created:
fun main() {
println("Hello, Kotlin!")
}
Breakdown of the Program Structure
1. fun
The fun
keyword is used to declare a function in Kotlin. Functions are reusable blocks of code that perform a specific task.
2. main
main
is the name of the function. The main
function is the entry point of every Kotlin program. When you run a Kotlin application, the execution starts from the main
function.
3. ()
Parentheses ()
follow the function name and are used to define the parameters the function takes. In this case, the main
function does not take any parameters, so the parentheses are empty.
4. {}
Curly braces {}
define the body of the function. All the code inside the curly braces is executed when the function is called.
5. println("Hello, Kotlin!")
println
is a standard library function in Kotlin used to print a message to the console. The message to be printed is passed as a string argument within double quotes.
Putting It All Together
When you run the program, the Kotlin runtime looks for the main
function. It then executes the code inside the main
function, which in this case is a single statement that prints "Hello, Kotlin!" to the console.
Conclusion
This simple "Hello, Kotlin!" program demonstrates the basic structure of a Kotlin program: function declaration using fun
, the main
function as the entry point, and the use of println
to print a message. Understanding this basic structure is essential as you progress to more complex Kotlin programs.