Skip to content

Kotlin

Running a Kotlin Program

To run the kotlin program write the code in your favorite edition and save the file with .kt extension. Now to  compile the code follow the following command in the terminal:

This will make a .jar file that is runnable and contain the Kotlin runtime library in it. Now to run the application follow the following command:

In Kotlin, the traditional “Hello World” program is very simple. Open a text editor and type the following code:

Save the file with a .kt extension, such as “hello.kt”. Open a terminal and navigate to the directory where you saved the file. To compile the program, type:

This will create an executable JAR file called “hello.jar”. To run the program, type:

You should see the output “Hello, World!” displayed in the terminal.

Basic Syntax:

In Kotlin, a function is defined using the following syntax:

For example, to define a function that adds two numbers, you could write:

You can also use the shorthand syntax for single-expression functions:

To call a function, you simply write the function name followed by the arguments in parentheses:

This will set the variable “result” to 5.

If a function does not return a value, its return type is Unit

Classes

In Kotlin, classes and objects are defined using the following syntax:

For example, to define a class that represents a person, you could write:

You can create an instance of a class using the following syntax:

You can access properties and call methods of the object using the “.” operator:

This will display the output “Hello, my name is John.” in the terminal.