Category: Kotlin

  • Basic Syntax

    Kotlin Program Entry Point

    An entry point of a Kotlin application is the main() function. A function can be defined as a block of code designed to perform a particular task.

    Let’s start with a basic Kotlin program to print “Hello, World!” on the standard output:

    funmain(){var string: String  ="Hello, World!"println("$string")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    Entry Point with Parameters

    Another form of main() function accepts a variable number of String arguments as follows:

    funmain(args: Array<String>){println("Hello, world!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    

    If you have observed, its clear that both the programs generate same output, so it is very much optional to pass a parameter in main() function starting from Kotlin version 1.3.

    print() vs println()

    The print() is a function in Kotlin which prints its argument to the standard output, similar way the println() is another function which prints its argument on the standard output but it also adds a line break in the output.

    Let’s try the following program to understand the difference between these two important functions:

    funmain(args: Array<String>){println("Hello,")println(" world!")print("Hello,")print(" world!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, 
     world!
    Hello, world!
    

    Both the functions (print() and println()) can be used to print numbers as well as strings and at the same time to perform any mathematical calculations as below:

    funmain(args: Array<String>){println(200)println("200")println(2+2)print(4*3)}

    When you run the above Kotlin program, it will generate the following output:

    200
    200
    4
    12
    

    Semicolon (;) in Kotlin

    Kotlin code statements do not require a semicolon (;) to end the statement like many other programming languages, such as Java, C++, C#, etc. do need it.

    Though you can compile and run a Kotlin program with and without semicolon successfully as follows:

    funmain(){println("I'm without semi-colon")println("I'm with semi-colon");}

    When you run the above Kotlin program, it will generate the following output:

    I'm without semi-colon
    I'm with semi-colon
    

    So as a good programming practice, it is not recommended to add a semicolon in the end of a Kotlin statement.

    Packages in Kotlin

    Kotlin code is usually defined in packages though package specification is optional. If you don’t specify a package in a source file, its content goes to the default package.

    If we specify a package in Kotlin program then it is specified at the top of the file as follows:

    package org.tutorialspoint.com
    
    funmain(){println("Hello, World!")}

    When you run the above Kotlin program, it will generate the following output:

    Hello, World!
    
  • Architecture

    Kotlin is a programming language and has its own architecture to allocate memory and produce a quality output to the end user.

    Following are the different scenarios where Kotlin compiler will work differently.

    • Compile Kotlin into bytecode which can run on JVM. This bytecode is exactly equal to the byte code generated by the Java .class file.
    • Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and generates a compatible code for JavaScript.
    • Kotlin compiler is capable of creating platform basis compatible codes via LLVM.
    • Kotlin Multiplatform Mobile (KMM) is used to create multiplatform mobile applications with code shared between Android and iOS.
    kotlin Architecture

    Whenever two byte coded files ( Two different programs from Kotlin and Java) runs on the JVM, they can communicate with each other and this is how an interoperable feature is established in Kotlin for Java.

    Kotlin Native

    Kotlin/Native is a technology for compiling Kotlin code to native binaries, which can run without a virtual machine. Kotlin/Native supports the following platforms:

    • macOS
    • iOS, tvOS, watchOS
    • Linux
    • Windows (MinGW)
    • Android NDK
    • Many more…

    Kotlin/Native is primarily designed to allow compilation for platforms where virtual machines are not desirable or possible, for example, embedded devices or iOS.

    It is easy to include a compiled Kotlin code into existing projects written in C, C++, Swift, Objective-C, and other languages.

  • Environment Setup

    Installing Kotlin command-line compiler

    One of the key features of Kotlin is that it has interoperability with Java i.e. You can write Kotlin and Java code in the same application. Like Java, Kotlin also runs on JVM therefore to install Kotlin on Windows directly and work with it using the command line You need to make sure you have JDK installed in your system.

    Verifying the Java installation

    To verify Java installation −

    • Open command prompt and verify the current version of Java using the javac version command −
    C:\Users\TP>javac -version
    javac 1.8.0_261
    

    If you doesn’t have Java installed in your system it generates the following error

    C:\Users\Krishna Kasyap>javac -v
    'javac' is not recognized as an internal or external command,
    operable program or batch file.
    

    You can install JDK by following the steps given below

    Installing JDK8

    • Open the following Oracle Java Downloads page.
    • Click on the JDK Download link under Java SE 8 section.
    JDK Kotlin
    • This will redirect to the page that contains JDK software for various platforms, select the desired version (.exe) and download it.
    Software
    • After downloading the file JDK file (assume we have downloaded jdk_windows-x64_bin.exe), start the installation by running it.
    JDK File
    • By default, Java will be installed in the path C:\Program Files\Java\jdk1.8.0_301\ you can change the path by clicking on the Change… button.
    Java Development
    • After the completion of the installation click on the Close button.
    Java Development

    Kotlin Command line compiler

    Kotlin command line compiler is available at the JetBrains Kotlin GitHub releases page.

    • Download the latest version.
    • Unzip the downloaded file and place it in the desired folder.
    • The Bin directory of the downloaded folder contains all the binary files to run Kotlin.
    Bin
    • Now, set Path environment variable to this folder.

    Setting the Path variable

    • Right click on My computer or This PC, select Properties.
    Path Variable
    • Click on Advanced System Settings.
    Advanced System Settings
    • Then, click on the Environment Variables… button.
    Environment Variables
    • In the Environment Variables window, under System Variables select the Path variable and edit the variables using the Edit… button.
    System Variables
    • Click on the New button and add the path of the bin folder of installed JDK and Kotlin folders.
    Edit

    To verify the installation, open command prompt and type java or javac command, if your installation is successful, you can see the output as shown below:

    Command Prompt

    Setting Kotlin environment using IntelliJ IDEA

    Kotlin is developed by the JetBrains that develops IDEs like AppCode, CLion, DataGrip, DataSpell, GoLand, IntelliJ IDEA etc.

    The IntelliJ IDEA internally have Kotlin plugin bundled with it. To develop Kotlin download and install IntelliJ.

    To install a recent version of IntelliJ IDEA:

    • Open JetBrains Downloads page, you can download the free community edition.
    IntelliJ Idea
    • If you run the downloaded file, it starts the installation process.
    IntelliJ Installation
    • Proceed with the installation by providing the required details and finally complete the installation.
    JetBrains
    • The Plugins tab of IntelliJ displays all the available plugins. By default, Kotlin plugin is activated, in any case if it is not activated. Open the plugin tab, search for Kotlin and install it.
    Plugin Tabs

    Creating first application

    • To create first application, click on NewProject.
    First Application
    • Select Kotlin/JVM and click Next.
    JVM
    • Name the project and select the desired location.
    Sample Application
    • Now, create a new Kotlin file under the source(src) folder and let’s name it as Test.
    Test
    • You can create a sample function as shown below. You can run this by pressing Ctrl + Shift + F10.
    Sample Function

    Setting Kotlin environment using Eclipse

    You can also execute Kotlin programs in eclipse to do so, you need to have “Eclipse IDE for Java developers” installed in your system. To do so, follow the steps given below.

    • Download the latest version of eclipse installer from the page: https://www.eclipse.org/downloads/
    Eclipse
    • Run the downloaded file and click on the Eclipse IDE for Java developers.
    Eclipse Installation
    • Select the installation directory and click on install.
    Directory
    • Open eclipse in the Help menu select Eclipse Marketplace.
    WorkSpace
    • Search for Kotlin and check all the matches and when you find Kotlin click on Install.
    Marketplace

    Creating a Kotlin application in eclipse

    Once you have installed Kotlin plugin in your eclipse to create your first application.

    • In the File menu click on Project.
    Project
    • This will take you to Select a wizard. Under Kotlin (dropdown menu), click on select “Kotlin Project” and click on the “Next” button.
    New Project
    • Then, enter the desired name for the application and click on Next.
    New Project1
    • Right click on the src folder of the created project click on other.
    Source
    • Select the Kotlin File wizard click on Next and name the file as Hello.kt.
    Kotlin File

    Your development environment is ready now. Go ahead and add the following piece of code in the “Hello.kt” file.

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

    Run it as a Kotlin application and see the output in the console as shown in the following screenshot. For better understanding and availability, we will be using our coding ground tool.

    Application
  • Overview

    What is Kotlin?

    Kotlin is a new open source programming language like Java, JavaScript, Python etc. It is a high level strongly statically typed language that combines functional and technical part in a same place. Currently, Kotlin mainly targets the Java Virtual Machine (JVM), but also compiles to JavaScript.

    Kotlin is influenced by other popular programming languages such as Java, C#, JavaScript, Scala and Groovy. The syntax of Kotlin may not be exactly similar to Java Programming Language, however, internally Kotlin is reliant on the existing Java Class library to produce wonderful results for the programmers. Kotlin provides interoperability, code safety, and clarity to the developers around the world.

    Kotlin was developed and released by JetBrains in 2016. Kotlin is free, has been free and will remain free. It is developed under the Apache 2.0 license and the source code is available on GitHub

    Why Kotlin?

    Kotlin is getting high popularity among all level of programmers and it is used for:

    • Cross-platform Mobile applications.
    • Android Application Development.
    • Web Application Development
    • Server Side Applications
    • Desktop Application Development
    • Data science based applications

    Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) and it’s 100% compatible with Java.

    Kotlin is used by many large companies like Google, Netflix, Slack, Uber etc to develop their Android based applications.

    The most importantly, there are many companies actively looking for Kotlin developers, especially in the Android development space.

    Kotlin Version?

    At the time of writing this tutorial on Aug 3, 2021, The current Kotlin released version is 1.5.21

    Kotlin Advantages

    Following are some of the advantages of using Kotlin for your application development.

    1. Easy Language − Kotlin supports object-oriented and functional constructs and very easy to learn. The syntax is pretty much similar to Java, hence for any Java programmer it is very easy to remember any Kotlin Syntax.

    2. Very Concise − Kotlin is based on Java Virtual Machine (JVM) and it is a functional language. Thus, it reduce lots of boiler plate code used in other programming languages.

    3. Runtime and Performance − Kotlin gives a better performance and small runtime for any application.

    4. Interoperability − Kotlin is mature enough to build an interoperable application in a less complex manner.

    5. Brand New − Kotlin is a brand new language that gives developers a fresh start. It is not a replacement of Java, though it is developed over JVM. Kotlin has been accepted as the first official language of Android Application Development. Kotlin can also be defined as – Kotlin = Java + Extra updated new features.

    Kotlin Drawbacks

    Following are some of the disadvantages of using Kotlin.

    1. Namespace declaration − Kotlin allows developers to declare the functions at the top level. However, whenever the same function is declared in many places of your application, then it is hard to understand which function is being called.

    2. No Static Declaration − Kotlin does not have usual static handling modifier like Java, which can cause some problem to the conventional Java developer.