A Quick Look at Kotlin Code

Program Entry Point

Let’s start by looking at the Hello World program introduced earlier. Kotlin’s basic syntax, like Java, starts from the main() function. The main function should not belong to a class and should be directly under a package. As in Java, the package name uses the style of reversing the domain name and separating sections with dots (.).

Kotlin source code uses the .kt and .kts extensions. .kt files are compiled by the Kotlin compiler, and .kts files are executed through Kotlin scripting support.

Hello World!

The program that prints Hello, world! is as follows. Add the .kt extension to the HelloWorld.kt file.

package com.devkuma.sample

fun main() {
    println("Hello, world!")
}

Output:

Hello, world!!!

To actually run it, use the Kotlin compiler or IntelliJ IDEA with the Kotlin plugin. If you want to run it simply, you can also edit and run Kotlin code in a web browser with Kotlin Playground.

main Command Arguments

The example above omits arguments from the main function, but arguments can be included as args: Array<String>.

As you can see from Array<String>, args is a string array, so it can receive multiple string values as parameters, and you can get the first parameter with args[0].
If there are no parameters, accessing args[0] causes an ArrayIndexOutOfBoundsException, but using the contentToString() method prevents this. When there are no parameters, this method displays an empty array ([]).

fun main(args: Array<String>) {
    //println("program arguments: ${args[0]}");
    println("Program arguments: ${args.contentToString()}")
}

Output:

Hello World!
Program arguments: []

Comments

There are single-line comments and multiline comments.

fun main(args:Array<String>){
    // Single-line comment
    /*
      Multiline comment
    */
}

Semicolon at the End of a Line

A semicolon (;) at the end of a line can be omitted. It is fine to include one, but it is often omitted.

println( "Hello!")
println( "Hello!");

Coding Rules

The following coding rules are used.

  • Use camel case for variable and function names, for example createObject.
  • Data types and class names start with an uppercase letter, for example String.
  • Function names and property names start with a lowercase letter, for example marginWidth.
  • Use four spaces for indentation.
  • For public functions, refer to Kotlin Doc documentation (KDoc).

String Declaration

// String declaration
val hoge = "aiueo"

// Type declaration is also possible
val hoge : String = "aiueo"

// Number declaration
val number = 1

Data types can be declared explicitly, but if they can be inferred without a declaration, they can be omitted.

String Templates

StringTemplate.kt

class Test {
    fun printStr():String{
        return "test"
    }
}

fun main(args:Array<String>) {
    val num1 = 34
    println("num is $num1")
    val test = Test()
    println("test function ${test.printStr()}")
}

In the println() function, you can use a variable directly inside a string by writing only the $ symbol.

Standard Output: print and println

PrintTutorial.kt

fun main(args: Array<String>) {
    print("한줄 출력")
    print("입니다. \n")

    println("자동으로 줄바꿈 해줍니다.")

    print("그래서 저는 여기에 표시됩니다.")
}

Output:

한줄 출력입니다. 
자동으로 줄바꿈 해줍니다.
그래서 저는 여기에 표시됩니다.

The print() method prints continuously on one line, and println() automatically inserts a line break.
If you add a newline character (\n) to the final string in the print() method, it creates a line break just like calling println().

Keywords

// Hard keywords 
as (cast)     as (import) as?           break 
class         continue     do           else 
false         for          fun          if 
in            !in          interface    is 
!is           null         object       package 
return        super        this         throw 
true          try          typealias    typeof
val           var          when         while 

// Soft keywords 
by            catch        constructor  delegate
dynamic       field        file         finally 
get           import       init         param 
property      receiver     set          setparam
where 

// Modifier keywords 
actual        abstract     annotation   companion 
const         crossinline  data         enum 
expect        external     final        infix 
inline        inner        internal     lateinit 
noinline      open         operator     out
override      private      protected    public 
reified       sealed       suspend      tailrec
vararg 

// Special identifiers 
field         it