Hello World Example

The most essential elements of any program, however, simple are variables and functions. You can include classes if you are working with an Object Oriented Programming language.
Kotlin supports both functional and object oriented aspects. In this session, we'll look at a simple Hello World example. Thus, even with that simple example, we'look at some of the language features and syntax that a hello world can typically show us.

//main function taking array of Strings
fun main(args: Array<String>) {
    //immutable and mutable variables respectively
    val name="Casini"
    var galaxy="Andromeda"

    //println
    println(name+" is moving to "+galaxy)
}

RUN/EDIT CODE

Five things to Learn from Kotlin's simplest Hello World

So what can we observe in the above example:

  1. Take note of the fun keyowrd. We normally use this keyword to declare functions in Kotlin. Fun isn't it?
  2. Take note of how we pass parameter to a Kotlin's function.Even more, tae note that the parameter name comes before the parameter type. This is unlike languages like java and C#. Kotlin: args: Array<String> Java: String[] args ;
  3. Take note that we don't have to specify a class to contain our function. Function can also be declared as a top level object.
  4. Take note of the println() function as opposed to System.out.println() in java.Kotlin's standard library makes this function more concise without boilerplate code.
  5. Take note that we don't have to specify semicolons to denote end of statements.
  6. Take note of how we create an array in kotlin, there is no special syntax to create an array. Think the square brackets in java and C#. In Kotlin, an array is just like any other class and so it's declared with Array class as the type.args: Array<String>

MORE EXAMPLES

EXAMPLE 1 : Object Oriented Hello World Example

class Person {
    fun hi() {
        println("Hi Julie");
    }
}

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

RESULT

Hi Julie

EXAMPLE 2: - OOP With Constructor Parameter

class Person(val name: String) {
    fun hi() {
        println("Hi, ${name}");
    }
}
fun main(args: Array<String>) {
    Person("Mike").hi()
}

RESULT

Hi, Mike