Kotlin – Hello world

(Last Updated On: September 20, 2017)

Introduction

What is Kotlin?

It is a new programming language built by JetBrains, and as you may already know, Google announced at Google I/O 2017, that they will now officially support this language. It is inspired by existing languages such as Java, C#, JavaScript, Scala and Groovy.

What are the advantages of using Kotlin?

  • it’s a more concise language (40% cut in the number of lines of code)
  • less NullPointerException errors by making all types non-nullable by default
  • New features like:
    • smart casting
    • high order functions
    • Coroutines
    • Lambdas, etc

Hello World, Kotlin

Let’s create a Hello World project. Create a new project by checking Kotlin option that is available starting with Android Studio 3.0 (Note! If you already have a project and want to convert it to Kotlin, Android Studio has an option to do this too, but we will talk about it in another post).

Step 1

File – New – New Project

Step 2

Step 3

Step 4

Step 5

Step 6

Notice that a kotlin-android plugin was added to the module gradle file.

Step 7

Also, notice these changes in the project build.gradle file.

activity_main.xml

MainActivity

Now, in the MainActivity class, the onCreate() method, looks like this:

As you can see there are changes in the writing (obviously :P):

  • instead of “MainActivity extends AppCompatActivity” now we have to use “:
  • onCreate is now a function
  • the onCreate parameters look like this now “savedInstanceState: Bundle?” (we will get more into this in other posts)

COOL FACT: Notice that we could set a text on our TextView without using findViewById()! We just wrote the id itself and set the text and that’s it. Cool, ha? 🙂