Wednesday 21 December 2016

Kotlin | Hello World


package com.kotlin

fun main(args: Array<String>) {
     println("Hello, World!")
}

How this program works?
fun main(args: Array<String>) { ... }

This is the main function, which is mandatory in every Kotlin application. The Kotlin compiler starts executing the code from the main function.
This function takes array of strings as a parameter and returns Unit.

The signature of main function is:

fun main(args : Array<String>) {
    ... .. ...
}

println("Hello, World!")

The println() function prints the given message inside the quotation marks and newline to the standard output stream. In this program, it prints Hello, World! and new line.

Comparison with Java "Hello, World!" program
Kotlin is 100% interoperable with Java. Here's an equivalent Java "Hello, World!" program.
class HelloWorldKt {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Few Important Notes
1. As Kotlin compiler creates the class for us, it is not mandatory to create a class in every Kotlin program, unlike Java.

If you are using eclipse, go to Run > Edit Configurations to view this class. If you named your Kotlin file HelloWorld.kt, the compiler creates HelloWorldKt class.

2. The println() function calls System.out.println() internally.

If you are using eclipse, put your mouse cursor on println and go to Open Declaration (Shortcut: F3), this will open Console.kt (declaration file) where we can see that println() function is internally calling System.out.println().

/** Prints the given message and newline to the standard output stream. */
@kotlin.internal.InlineOnly
public inline fun println(message: Any?) {
    System.out.println(message)
}
Related Posts Plugin for WordPress, Blogger...