Moving to Kotlin for Android Mobile Applications

Anyone currently developing Android applications in Java should start migrating code to kotlin.  It is that simple, the argument for this position, as outlined below, are compelling. However, there are many people who current develop apps using a tool other than Java, and for these people, the situation is far more complex, and I will also list the arguments against a move to kotlin at this time for apps not currently in Java.

Consider the following arguments for moving java apps to kotlin:

Google has announced kotlin as a ‘first class’ language for Android, and at the announced stated that kotlin has many features that make kotlin the language of choice for android development

  • kotlin and java code can co-exist, and an application can migrate to kotlin file by file or even class by class ensuring no delays during migration
  • there is automatic conversion from java code to kotlin code to enable almost automated conversion
  • all main development environments for java (Intelij, Android Studio, Eclipse) also support kotlin, and the end-to-end toolkits are the same for java and kotlin projects

Now consider the points against in the different situation for non-java android apps:

  • non-java solutions predominantly support android and iOS from the same code-base, kotlin support for iOS is at release 0.2 and not yet mature
  • code cannot be mixed, so the entire application must be converted before any results of the conversion are available, testable, or able to be evaluated
  • there is no automated code conversion other than from java
  • significant document of kotlin is based on documenting only changes from java
  • tool chains for kotlin significantly different from those of non-java android tool chains and these tools must also be learnt
  • while the ‘gradle’ build tool generally favoured in the industry for building kotlin apps in moving to kotlin based scripts reducing the new steps to be learnt,  this ‘kotlin script gradle’ is also in pre-release and current documentation is targeted at migrating existing gradle users, not new users

Two of these ‘against’ points are simply about timing, as they relate to components not yet at version 1.0.    The ‘against’ list will get less and less compelling over time,  but if converting a project, converting a ‘non-java’ android app is a big step.

 

 

 

 

Implementation: what is a practical approach?

Any software team who is considering moving to kotlin, must by definition, be currently using at least one alternative language.  To change languages, and ecosystems, is a big step.  One of the key features of kotlin is how easily and seamlessly a project can migrate from java.  Currently, that same ease of migration is far less real from outside the java ecosystem.

Cold Turkey? Or step by step?

On rare occasions, there may be the opportunity to commence a complete new project and build each component with no basis on any legacy system.  If starting an entirely new project but not already experienced in kotlin, it will still require a huge leap of faith to start an entire development in kotlin.

More often, and in the project we are currently working with, the realistic path is to choose system components that can move to kotlin.

The candidates:

Individual pages discuss these sections, but the spoiler alert is that mobile/android development may not be the logical first choice it would on the surface seem.

Kotlin DSL templates with Python (or any other) Server

The Concept: A replacement template engine written in Kotlin DSL

Kotlin can replace the template system for a python server, or ruby server, or any other server, with no change to the server other than the template system, regardless of what language is used for the server itself.

This allows replacing mako, or jinga2,  Django templates, with kotlin DSL templates.  No kotlin or jvm installation is needed on the server, as the kotlin dsl templates can run as javascript in the browser.

Why? : A more dynamic and concise solution

Template engines are generally considered a method of producing ‘dynamic’ web pages.  While a ‘static’ web page always displays the exact same html, templates produce html which reflects the data presented to the template.  For example, a ‘member’ page will have the information for the member currently logged in,  while a static home page will display the same information to everyone.

However pages generated by templates are not necessarily ‘dynamic’ in a web2.0 manner.  The page is ‘generated on the fly’ by the template engine, but does not necessarily run dynamically in the client browser.  To the client browser, the page appear static.

These kotlin DSL templates are a complete rethink of how templates work, and inherently produce code that is also dynamic on the browser and the entire system makes adding true dynamic content far simpler.

Further, the description of page content becomes more concise than with conventional templates.

More Languages? Or Less?

It could be seen that adding kotlin to do templates means adding yet another language to the toolkit in use with a project, however this is only proposed as substitute for mako, jinga2 or some other template language, so there is also one language no longer required.

Kotlin is far more complex than any template language, but using the kotlin DSL as described here does not require learning the full kotlin language.   The further benefit is that learning a template language just for templates has no other uses, while it is very likely there are other possible uses of kotlin (e.g. Android?)  within a project.  If kotlin has an additional use within the project, then using kotlin for templates could mean one less language overall.

How do these Kotlin DSL templates work?

A conventional template is like a more powerful version of the python format function.

Consider:


"person: {name} age: {age}".format(name="fred",age=35)

This is equivalent to the string being a template that is supplied data in the form of the ‘name’ and ‘age’.  The string is modified by the data, to produce a final string.  Templates just allow more power with modifying the string.

The kotlin DSL templates I am discussing, actually run in the browser, not on the server.  The template can look similar to html, but it is code, not a string.  Using simple python format statement for a simple example of templating, the template might be:

<html>
    <body>
person: {name} age: {age}
</body>
</html>

and by processing the template with our data, the final page is prepared on the server and sent to browser.

However with the kotlin templates discussed, our layout inside the ‘html’ tag, is not present inside html sent to the browser, and in place of the content will normally be an emply placeholder ‘div’ tag.  Javascript code to instance the ‘body’ and ‘p’ tags inside the placeholder ‘div’ is sent as the template, and this code will read the jsondata (where present) and provide the correct content inside the div tag.

Different perspective?  HTML vs DOM

One perspective is to think of a web page and the html as basically synonymous.  Another perspective is to think of the web page is the DOM, and html is just data describing that DOM.  With this second paradigm, we could consider: “what if the DOM itself is described by javascript, not by the html code?”

This makes our web page:

<html>
  <body>

<!-- first a json script to hold any json data  -->
<script id="data" type="application/json">{jsondata}</script>

<!-- now here is the div where our main content will be added -->
<div id="page"></div>
<!-- now the script for the page content >
  <script src="{templatename}"></script>

  </body>
</html>

As you can see, the html to describe page content just an empty ‘div’ in the page.  So the DOM must get the page content part of  DOM from the kotlin DSL.  In fact this same html above, is now used for every page on the web site. The only part that changes is the {jsondata}, and  changing the {templatename} to the actual values for these to be used.  The sample above is perfect for using with a python format to substitute actual names,  but in testing if just sending the html file, then just set these to the values for testing.

What does the Kotlin DSL look like?

Of course the page above does nothing without the javascript,  because the javascript it generating the tags for the main part of the web page.   The only HTML is outside skeleton, and the main content of the page is described in kotlin DSL instead of in HTML.  Here is a very simple ‘main part of the page’ with just a

text

with a heading of ‘heading’ for content.

val div = document.create.div {
h1 { +"heading" }
    p { +"text" }
}

The document.create.div is needed for the very outer layer, and all the html tags inside become very clean and simple.  Using data within the page, or having tags produced in a loop, is all automatic by just using more of the kotlin language.

See the link: kotlin javascript tutorial for more on the DSL for html and how to configure Intellij and install the jar file for kotlinx.html

For a working example of the template scheme described on this page, see the ‘hypothetical programmable calculator’ as described in the page Machine code and Global Memory.  The code for the calculator with code for a kotlin DSL template example can be found in the repository.

Machine Code, Global memory, the Stack and the Heap

Today we computers that have multiple ‘cores’ (in fact complete processors) on a single chip. But one way to understand the fundamentals of computers is to analyse far simpler computers from the past.  This section will review those very fundamental concepts in term of a hypothetical programmable calculator, one of the very first ever popular ‘mini-computers’, the PDP-8 from 1965, and the Intel 8080 cpu from 1974 that still influences the instructions of intel Xenon and ‘Core’ processors in 2017 .

The JavaScript (with Kotlin source code) version of the ‘hypothetical programmable calculator’ is available here.  I will also add links to emulators for the PDP 8 and 8080.

Sections:

Machine Code and Global Memory

sdl453269107_1375355122_image1-1310fTo understand how memory works, it can be useful to consider how the CPU itself works, and what follows from that is how memory works.  Languages build on the underlying principles and automate using the different types of memory.

This page uses a ‘hypothetical programmable calculator’ (Magic Calculator) to illustrate the principles of how instructions are executed and how global memory works with the instructions described below.

 

Hypothetical Programmable Calculator

How does a CPU work?

The example of the ‘hypothetical programming calculator is used for ‘how does a  ‘Central Processing Unit’ (CPU) work.  The working memory inside a CPU is the CPU ‘registers’, and the value displayed on a calculator screen is very analogous to simple computer with a main register.  For this exercise, consider this displayed value as the ‘a’ register (Many original computer did have an ‘a’ register, or ‘accumulator’ register, and some even provided a continuous display of the value of this register).  To add two numbers on a calculator, we enter the first number to our display or ‘a’ register, then activate ‘+’, which has to store the operation as plus, and save the first number into a second register which we can call ‘b’. Then we enter the second number into the ‘a’ register (or display), and with the ‘=’ we do the stored operation with add ‘a’ and ‘b’ and leaves the result in a.

So we have some program steps, but how do we ‘run’ these steps? Well first we need some memory.

Program Memory and program counter

Many calculators have one or more ‘memories’.  Our programmable calculator is going to have 100 memories!  The simplest calculators have one memory, and you can save from the ‘a’ register to the memory, or load from the memory to the ‘a’ register.  On some calculators you can even add the ‘a’ register into the memory, but I digress. The big thing with our programmable calculator, is that values in memories represent instructions.  Number ‘1’ when used as instruction could be our ‘+’, number ‘2’ our ‘=’ and number ‘3’ could mean ‘set a,n’  to set a from value in the memory following the instruction.   To make this work, we need a new register, a ‘Program Counter’ register for pointing to instructions.  Every time we load an instruction, or load information with the ‘Program Counter’, the program counter increases by 1.

So our program to add 7 and 8 (in memory locations 0, 1, 2, 3, 4, 5, 6 )now looks like:

  • 3  7  1  3  8  2  0  (enter this string into the emulator ‘code’ field)

The steps are:

  1. The “program counter (PC) starts at zero so the instruction at zero, (3- load a) is run, and this instruction loads the next value from the memory location specified PC register (and again adds one to the register), so the result is the ‘7’ from location ‘1’ is loaded into ‘a’ and 7 is displayed.
  2. The PC register is now 2 (increased to 1 after loading the ‘3’ – load instruction, and again increased to 2 as the load instruction loaded the ‘7’ from location 1.  The plus instruction sets operation register to ‘add’ and copies the ‘7’ from the ‘a’ register to the ‘b’ register.
  3. The ‘load’ instruction (3) from location ‘3’ is loaded from the program counter and this instruction then loads the ‘8’ from memory location 4 into ‘a’ register
  4. the ‘=’ instructions (2) from memory location ‘5’ is loaded and this causes the ‘7’ from ‘b’ to be added to ‘a’ so the calculator then display our answer: ’15’
  5. the ‘stop’ instruction (0) from memory location 6 causes our program to stop.

This simple example illustrates how a program actually runs in a computer. The main memory can have both data and instructions.

Adding global variables: the instructions.

Currently the binary program for the ‘programmable calculator’  just does the equivalent of  ‘7 + 8’ in python.

This is only useful because we can see the ‘a’ register on the calculator display.  The equivalent of ‘7+8’ being useful in ‘idle’, because idle prints the answer. Now consider the program ‘answer = 7 + 8’.  This program stores the answer in a variable.  The previous program is stored in  7 memory locations, so there is lots of free memory locations for variables.   If we plan to use half of the memories for code, and half for variables, then all memories below 50 would hold code and numbers used inside code, and memories 50 and above would be for variables.

None of the current instructions use variables, so consider  two new instructions, load a,(n) and  save a,(n) to load ‘a’ register from the memory location we want, or save the ‘a’ register. The ‘load’ (instruction code 4)  and ‘save’ (instruction code 5) will both use the memory following the instruction to specify which memory is to be loaded or saved.

Currently the ‘Magic Calculator’ does not support these last two instructions(load and save), but if desired for experimentation, this could be added.