1
Write a post

Android: Kotlin Vs Java by Example (Part 1, Simple Hello world)

Published Jul 29, 2017Last updated Jul 30, 2017
Android: Kotlin Vs Java by Example (Part 1, Simple Hello world)

In the second quarter of this year, google came about promoting Kotlin as one of the official language of android. All before then, it has been java winning all the way like the old man playing knick knack from one to ten and rolling home. Java is one very good age long language that has stand the test of time. It's about twenty-five years old language that does object oriented very well than it predecessor C++. It has come a long way and when android was coming they also adopt java as an official language for writing android native application. Java is cool all the way. But innovations, trends, ways of doing things better and some disrupts will make you feel like nothing last forever. Truly, nothing last forever. Here come the announcement of mouth watering Kotlin. I choose to salute those Jetbrain guys. They packed Android studio too well over the features packed Eclipse and the Simple elegant Netbeans. I still remember how they wooed me with hypnotise ItelliJ IDEA that makes me forget there is Netbeans IDE.
Interestingly, these guys came up with Kotlin and Google be like "waoo!! How did u do that"! How-did-you-do-it--meme-46752.jpg

About me

For someone like me, who love trying out new things and appreciate innovations despite my big love for java like Romeo would ever show love to Juliet. I still prefer trying Kotlin out. And guess what, what if Kotlin evolves totally over java like swift does to objective c. I don't want it to be too late before I started doing something with new technologies like this. Morever, I subscribe to this opinion here https://blog.mindorks.com/should-i-learn-kotlin-or-stick-to-java-3a73c3580ac3 as a ninja developer.

My Hello World

Well in this series of tutorial, I will be reviewing some features by taking a sample project - From simple Andoid Hello World Application to a To Do app, database driven apps, push notifications and even socket powered apps among others. I beleive we will appreciate the new way more by also exploring little ways of doing things in the old way and comparing it to the new way.

Tech stack

For this tutorial, I will be using android studio( the officail IDE for android development). You can also use eclipse or any favourite IDE if that you have preconfigured for android development.
If you are running Android less than 3.0. You will have to download kotline plugin by going to File -> Settings -> OR Android Studio -> Preferences on Window or Mac respectively. Then on the poped up dialog, click plugins, install jetBrains plugin Screen Shot 2017-07-22 at 2.37.45 PM.png

The Simple Helloworld project

Now You will be creating the project like you will normally do in android studio.

Step 1. create a new Android project in your android studio by going to File-> New -> New Project
You should have a dialog that looks like this.
Screen Shot 2017-07-22 at 12.57.24 PM.png
Change the application name,

Step 2. click Next, on the API level(for this tutorial) leave default configuration which is Phone an tablets option been checked and and with minimum SDK options selected as API 11 Andoid 3.0(Honey Comb) however, this should be determined by minimum api level of Android OS that you want your app to be able to run on. Press next and ...

Step 3. ...then select the Blank Activity on the new dialog. Press Next and change the activity name if you like. For this tutorial, I left mine as default. If you are using Android 3,0 You will be given an option to use Kotlin or Java but if u have downloaded Kotlin plugin as described above. You will be creating java version of the app first and later convert it to kotlin.

In our App module structure, we will be working on adding some UI component to the Main Activity. So navigate to the main_activity.xml by expanding the folder structure to the left of your Android Studio and doble click it to edit this in the master pane
Screen Shot 2017-07-22 at 2.53.31 PM.png

Now you should have a UI you can drag and drop component on with a TextView tagged "hello world" on it by default. Drag a Button from the widget pane to the screen. Double-click the button you dragged to the screen and you will have a popup where you can give an id to the button. You can also make this changes by either changing the Id and text from the inspector you have on the right after clicking a component or by press and hold cmd on mac or ctrl on PC while you click a component, this will change to text mode editing with your cursor on the xml representation of the button so paste

android:id="@+id/helloButton"

in the xml repesenting the button component such that you can have an xml block for the button as this

    <Button
        android:id="@+id/helloButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/say_button"
        android:visibility="visible"/>

Do thesame for the the initial TextView on the UI by changing the ID to helloText. Such that you will have a xml code block representing the textView as it is bellow

    <TextView
        android:id="@+id/helloText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="36sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.48"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.121" />

You can freely move and use inspector pane to position you button. I will touch layout in details in one of post, where I will review most UI layout in android and how to use them. But for this tutorial.You can edit your button's xml block code to look like this

<Button
        android:id="@+id/helloButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/say_button"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.738" />

thereby adding the last six line to hold it in position.This applicable to a constraint layout which comes by default when u select Blank activity.
Now we should have a UI like this one if we toggle back to design mode by using the toggle button below the editor.
Screen Shot 2017-07-22 at 3.25.54 PM.png

The above is the same for creating UI activity in doing this with java or kotlin

Now to the Duke (Java - the old way)

This is what we will be requiring as our code to power the activity_main.xml UI by wiring it up.
Navigate to the MainActivity.java and open it in the editor. We should have an initial java code as this

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

I will like to be able to set another text to my TextView after clicking button the whose text is "Say Hello". So I will modify the javacode and make it to look like

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button sayHello;
    private TextView hello;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hello = (TextView)findViewById(R.id.helloText);
        sayHello = (Button)findViewById(R.id.helloButton);
        
        sayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hello.setText("Hello Java. I am currently running on JVM");
                hello.setVisibility(EditText.VISIBLE);
            }
        });
    }
}

The added code are

import android.widget.Button;
import android.widget.TextView;

Importing the Button class and TextView class from the android.widget package. Also add

 hello = (TextView)findViewById(R.id.helloText);
 sayHello = (Button)findViewById(R.id.helloButton);

to inject ui component into the MainActivity class as field that I can manipulate in my code. So I also add an on click event listen to the button with corresponding action to trigger as written bellow.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hello = (TextView)findViewById(R.id.helloText);
        sayHello = (Button)findViewById(R.id.helloButton);
        sayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hello.setText("Hello Java. I am currently running on JVM");
                hello.setVisibility(EditText.VISIBLE);
            }
        });
    }

So the complete activity in java looks like this.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private Button sayHello;
    private TextView hello;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hello = (TextView)findViewById(R.id.helloText);
        sayHello = (Button)findViewById(R.id.helloButton);
        sayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hello.setText("Hello Java. I am currently running on JVM");
                hello.setVisibility(EditText.VISIBLE);
            }
        });
    }
}

and the below code

sayHello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hello.setText("Hello Java. I am currently running on JVM");
                hello.setVisibility(EditText.VISIBLE);
            }
        });

can be replace with lambda expression if your environment has been configured to support java 8 features

The Kotlin way of writing the above codes written in java

So our MainActivity.java file can be written in MainActivity.kt as bellow

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.EditText
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    private var sayHello: Button? = null
    private var hello: TextView? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        hello = findViewById(R.id.helloText) as TextView?
        sayHello = findViewById(R.id.helloButton) as Button?
        sayHello!!.setOnClickListener {
            hello!!.text = "Hello Kotlin. I am currently running on JVM"
            hello!!.visibility = EditText.VISIBLE
        }
    }
}

Comparism and Changes

In the begininng, not much has change in the way we import packages. Since this runs on java virtual machine and most of it's packages are use with same android sdk packages.

  • Statement terminator : We have this new way of writing a complete statement without semi colon to show the end of statement i.e
    import android.os.Bundle;  // the usual way of indicating a statement 
    
    import android.os.Bundle	// the Kotlin way without ;
    

The feature is said to be forgiven language by some people, I remember most of the time writing java then as a beginner and often forget to include semicolon ; Thus always comes up with syntax error. I think it's good you can now make it optional in kotlin

  • pulic keyword in class declaration :
    In java, it's a doctrin to have the class name that has the same name as file name to be a public class. It's not neccessary in kotlin if you are inheriting a class. It assummes thesame visibility modifier for child class

    // java way of declaring a public class
    public class MainActivity extends AppCompatActivity { 
    }
    

    the kotline equivalent without "public" - visibility modifier

    // the kotlin way of class declaration
    class MainActivity : AppCompatActivity() { 
    }
    

    However, if you have any reason to make the child class or method(function) have different visibility then you can specify visibility/access modifier in kotlin; private, protected, internal and public. internal isn't in java.

  • Inheritance and It's Keyword
    I want to believe we still followed the same principles of inheritance here in Kotlin. However the "extends" keyword is a five character word for implimenting inhentance in java but this has been replced with ":” keyword in kotlin

    //the java way to implement inheritance using extends keyword
    public class MainActivity extends AppCompatActivity {
    }
    
    //the Kotlin way to implement inheritance using : keyword
    class MainActivity : AppCompatActivity() {
    }
    

    However, you will have to specify the "()" just after specifying the super-class to inherit from. So I ask myself why adding this two bracket. Thoughtfully, I think this will take care of case of polymorphism constructors of a class. The kotlin documentation for inheritance affirms this. Hence you will be able to pass initial value of a constructor to it instead of the java way, with the option of implementing the instance of such parent class to be inherited an introducing super in it constructor. You contructor will however be taken care of in kotlin by calling init() function in your class.

  • Nullable variable: This should be a topic on it's own. To keep this short, you declare a nullable variable field in java like this

    private Button sayHello;
    

    and further assign value to it like in constructor or method like this

    sayHello = (Button)findViewById(R.id.helloButton);
    

    You will want to do this in Kotlin as follow

    private var sayHello: Button? = null
    

    and further assign value to it like in constructor or method like this

    sayHello = findViewById(R.id.helloButton) as Button?
    
  • Overidding the methods of a supper class in java with @Override keyword will now be overriden with the keyword override in kotlin. The below code show the overriden of onCreate which is the first method to be invoke in a running activity while creating such activity in android

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
    }
    
  • Type Casting
    In java, you want do type convertion from a particular data type to another. This is know as casting and you can do this as shown in the below sample code adapted from our simple helloworld project.

    sayHello = (Button)findViewById(R.id.helloButton);
    

    We normally do casting with (Your Type) written before the actual value to be casted. Note that "Your Type" means the data type to convert to.
    In this case we are casting a View type that was retrive using it unique id with the method findViewById . The equivalent in Kotlin is

    sayHello = findViewById(R.id.helloButton) as Button?
    

    So Kotlin made casting easier by introducing a keyword "as" which make it tends toward natural language. We have seen most recent languages using this approach for simplicity.

  • Setting properties of an object.
    We can set property of an object in java using set method as defined by the Class of the object instaciated. Looking at the sample codes below

    hello.setVisibility(EditText.VISIBLE);
    

    the setVisibility method is not needed to set property as you will want do this by changing visibilty property and assign corresponding value to it. I.e

    hello!!.visibility = EditText.VISIBLE
    
  • Gradle changes
    There some changes to graddle dependencies at app level and project level.
    Navigate to your graddle to find this or add it if not yet on your dependency for Kotlin. At app level(module)

    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    

    At project level

    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    

    You will find these in the dependency of app gradle and project gradle scripts respectively.

After following this approach and build a complete hello world project. Click run, you app should change the text of the text view to the given text on clicking the added button.

Conclusions, Tips and advice

Kotlin brought simplicity to android developement. We have seen these in there approach to inheritance, casting keyword, redudant semi-colon which most recent languages like javascript, swift among others also consider not neccessary.

I think Kotlin is easier and simple to learn than java but the current disadvantages is that there not much documentation and online learning resources yet as you will have thousands of learing resource all over the internet for java. However, the good part is that people are here for you to take up your challenges in building android app with kotlin or learning kotlin.
Another good side of it is that, they are good way to get good stackoverflow reputations both for the questions asked and the solution proffered, codementor's ratings and reviews from mentee and a good way to start career in kotlin. So in all, I think it won't be bad to try out new things with kotlin for android beginer, Intermediate and or expert developers.

More tips will be to use Intelij IDEA or Android studio in writting kotlin as they are indeed helpful both for beginer and expert. I found these intellij IDE given good code suggestion even while you still want to code like you use to do with your java backgound.

Final thoughts and next steps

Watchout for the next tutorial on how to build a simple todo application. This will involve CRUD operations on one of the embeddable android database.

Regards

Discover and read more posts from Joshua Aroke
get started
Enjoy this post?

Leave a like and comment for Joshua

2
Be the first to share your opinion

Get curated posts in your inbox

Learn programming by reading more posts like this