Let’s learn Kotlin by building Android calculator app

One of the biggest news of Android world in 2017 definitely became Kotlin. This is new programming language from JetBrains which has been announced as official Android development language during Google I/O 2017 event. So there are no more excuses to make for not learning it. In this post I will share my findings on Kotlin and show you how to build small Android calculator app using this new language.

 

Why should you want to switch to Kotlin?

But first lets talk about any questions or doubts that could developer have to start using Kotlin. I won’t lie, I had all these myself, but after some research managed to find all the answers. Main question for me was why the hell do we need Kotlin when we have already reliable and one of the most popular language in the world Java? Answer here is so predictable. We all know that Java is already old language which is not changing a lot and fast enough, so it don’t have modern programming language features compared to other languages. Meanwhile Kotlin is really modern, with it you can write more safer and more functional code which besides being shorter manages to do more than written in Java. It is is designed with the idea to be just a better language than Java. Sounds good? Another question that comes to my mind is if Kotlin is already finished language, can we trust it to use in real life projects? You know sometimes to rush and chase the latest technology is not the best idea while it’s just half-baked. However Kotlin language first appeared on 2011. First stable Kotlin version was released only on 2016, so as you see it was developed for really long time until matured to reliable complete language. Finally I bet you would like to know how easy is to start using Kotlin in your Android projects? After trying myself I was really surprised to find out how many effort is made to have as easy transition from Java as possible. Most amazed I was with the fantastic feature inside Android Studio, our daily IDE used for Android development work, to convert from Java to Kotlin code automatically. If you are new to Kotlin this will be really helpful during your first steps while you get used to the language. Besides Kotlin is fully interoperable with Java code, which means that you can create mixed projects with both Kotlin and Java files coexisting. So you can start gradual migration from Java to Kotlin with your projects. Also please think about the idea that you can confidently expect best compatibility for Kotlin language with Android Studio and always up to date support. Why? Because Kotlin is designed by JetBrains, company known for creating IntelliJ IDEA, a powerful IDE for Java development. And Android Studio is based on IntelliJ. Moreover Google announced first-class support for Kotlin on Android, which means all their libraries, frameworks, features should work smoothly with the new language.

 

 

First Kotlin project – simple calculator app

Ok do you recognized my idea of importance to switch from Java to Koltin as soon as possible? Are you already motivated to try Kotlin building real app? For my first experiments with Kotlin I decided to go with the plan of creating simple calculator app. It’s one of my most often used applications whether it would be a personal computer or mobile phone. Actually between all these different platforms that I use, my favorite representation of calculator is on Windows 10. What I like in it that it shows nicely your recent actions and then stores your history.

 

So I decided to recreate it’s standard version on Android using Kotlin with all these my mentioned features included, which became more challenging than I thought at first time, but after all I reached nice result that I share with you.

Prototype Android app of Windows 10 style calculator with memory and history actions written in Kotlin.

 

You can dive to the code directly on GitHub to check it out how it was done.

 

Kotlin differences and advantages over Java

Kotlin language comes with many differences and advantages over Java that you will notice. Let’s have a look to some of them that I have faced immediately while working on my calculator app project:

  • We don’t use semi-colons at the end of the sentences anymore. This is simple one and the first thing I noticed instantly. 😉 Also it is recommended practice by IDE which warns about that.
  • When extending a class or implementing interface, you replace Java’s extends or implements with a colon, and then attach the name of the parent class or interface. Also classes are final by default, and can be extended only if it’s explicitly declared as open or abstract.
    // Extends AppCompatActivity class and implements Listener interface from HistoryActionListDialogFragment.
    class MainActivity : AppCompatActivity(), HistoryActionListDialogFragment.Listener { 
    ...
    }
  • In Kotlin defining parameters is vice versa to Java. Here first we write the name and then its type.
  • Variables defined by two different keywords var which means variable value can be changed and val which means that value cannot be changed. Also compiler is smart enough to recognize type of variable without declaring it as Kotlin is a strongly typed language that supports type inference.
    private var currentNumber : Double = 0.0 // Value can be changed.
    private var historyText = "" // Recognize type of variable without declaring it.
    private val ZERO : String = "0" // Value cannot be changed.
  • Functions are defined using the fun keyword instead of void. Function’s name comes before its type, which is opposite to Java.
  • Kotlin is null safe. You decide whether an object can be null or not by using the safe call operator – question mark. By default it cannot. We avoid a lot of defensive code which we used in Java just to check whether something is null before using it just to avoid unexpected NullPointerException.
    // If ? is inserted after any type name, we have explicitly instructed the compiler that the value of the type can either store an object reference or can be null.
    private var mListener: Listener? = null
    ...
    // Operator with !! allows to bypass nullability checking by the Kotlin compiler.
    mListener!!.onHistoryItemClicked(resultTextView.text.toString())
    ...
    // Functions are defined using the “fun” keyword. 
    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Safe call operator ? added to the variable before invoking the property instructs the compiler to invoke the property only if the value isn't null.
        when (item?.itemId) {
            ...
        }
    }
  • Has lambda expressions which allows reducing the amount of code needed to perform some tasks. The common example is adding a click listener to a button with one line instead of multiple lines in Java.
    button1.setOnClickListener {onNumberButtonClick(ONE)}
  • Newly introduced property modifier lateinit identifies that the property should have a non-nullable value and its assignment will be delayed. This is very handy when we need something else to initialize a property, but we don’t have the required state available in the constructor or no access at that moment.
    private lateinit var mData: ArrayList<String>
    ...
    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
            // Initializing an ArrayList in one line when fragment is already attached to Activity and string resources are available to reach.
            mData = ArrayList<String>(Arrays.asList(getString(R.string.no_history)))
    ...
    }
  • Meanwhile also new keyword lazy means that your variable should not be initialized unless you use that variable in your code. Have in mind that it would be initialized only once and after that always the same value used.
  • Kotlin has extension functions and properties. This adds new functionality or properties to a class even we don’t have access to modify the source code of that class. So if you ever wished that a class should have a function or a property that was not available, now you are free to create one. This is such a nice feature clearly showing that it is a modern programming language. 🙂
    // Extension function created to add special behaviour to our Activity.
    // Here keyword lazy means it won’t be initialised right away but the first time the value is actually needed.
    fun <T : View> Activity.bind(@IdRes idRes: Int): Lazy<T> {
        // Function will be called only by the main thread to improve performance.
        return lazy(LazyThreadSafetyMode.NONE) { findViewById<T>(idRes) }
    }
    ...
    // Than we use this function to assign button, because once done its value won't change.
    // Keyword by is delegate, which adds a special behaviour to a property.
    private val button0: Button by bind(R.id.button_0)
    ...
    // Extension property provides similar mechanism.
    // Note that you have to define a getter method on your property for this to work.
    private val Double.sqrt: Double get() = Math.sqrt(this)
    ...
    // Later we use this property to find square root of the provided number.
    thisOperationNumber = thisOperationNumber.sqrt
  • Statement if..else is also as an expression in Kotlin as it has the ability to assign a variable from the returned value of the statement.
    // In Kotlin there is no more conditional operator ? : like it is in Java, which is used as a shortcut for setting a single variable to one of two states based on a single condition. Here everything can be conveniently done using if..else statement.
    // In Kotlin, using the equality operator == will call the equals method behind the scenes, so it's totaly acceptable to use it for string comparision.
    currentValue = if (currentValue == ZERO || isFutureOperationButtonClicked || isInstantOperationButtonClicked || isEqualButtonClicked || isHistory) number else StringBuilder().append(currentValue).append(number).toString()
  • As a replacement for the familiar switch statement Kotlin offers new expression when which has more powerful features and is more concise.
    // Compared to switch/case statement in Java, here using when statement the argument can be literally anything, and the conditions for the branches too.
    // For example, Java (before version 7) does not support string in switch/case and you can achieve the desired result only by using an enum. 
    // However in Kotlin these restrictions are gone.
    private fun onInstantOperationButtonClick(operation: String) {
        ...
        when (operation) {
            PERCENTAGE -> {
                thisOperationNumber = (currentResult * thisOperationNumber) / 100
                currentValue = formatDoubleToString(thisOperationNumber)
            }
            ROOT -> thisOperationNumber = thisOperationNumber.sqrt
            SQUARE -> thisOperationNumber = thisOperationNumber * thisOperationNumber
            FRACTION -> thisOperationNumber = 1 / thisOperationNumber
        }
    }
  • Kotlin has string templates.
    // Strings in Kotlin can include references to variables that are interpolated.
    // In addition to simple variable references, they can also include any expression enclosed in curly braces.
    // Also you can still do the string concatenation if you like using plus sign.
    Toast.makeText(applicationContext, getString(R.string.memory_added_toast) + "${formatDoubleToString(memory)} + ${formatDoubleToString(thisOperationNumber)} = ${formatDoubleToString(newMemory)}", Toast.LENGTH_LONG).show()
  • Kotlin doesn’t have checked exceptions but instead all exceptions are unchecked. That’s the main difference between Kotlin and Java exception mechanisms. Exceptions are not explicitly declared in the function signatures, as they are in Java. If we feel that exception might arise even if it is not enforced by the Kotlin compiler, we should handle it by surrounding the method with with a try...catch block. Useful annotation called @Throws in Kotlin might come in handy when you still want to add the possible exceptions that might be thrown to a method signature.
    @Throws(IllegalArgumentException::class)
    private fun onNumberButtonClick(number : String, isHistory : Boolean = false) {
        ...
        try {
            currentNumber = formatStringToDouble(currentValue)
        } catch (e: ParseException) {
            throw IllegalArgumentException("String must be number.")
        }
        ...
    }
    

 

Where to learn

Here I pointed out just a few things, but there are so much more new features in Kotlin that makes this language different from Java and really modern one. To find out all of them and to learn Kotlin in general I would like to recommend amazing book which I have read myself – “Kotlin for Android Developers” by Antonio Leiva. If you feel that reading a book is too slow and too boring for you than any online course could be best alternative. You could try one from my favorite provider Pluralsight called “Kotlin Fundamentals” by Kevin Jones. After watching it I found out this to be made really professional with deep language coverage, and also as a great addition to reading a book.

 

My advice

I hope you will find this small Android calculator app code useful while exploring various Koltin language projects over internet. But remember that really to learn new language you need to start building something by your own. Happy learning and coding in Kotlin! Don’t forget to share your projects too.

 

Check out project on GitHub

 

This post was also republished on Medium. Show your support by clicking the clap button 👏 on the story page here. 😇🙏

Share your thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.