--

Friday, 2 February 2018

Kotlin - Chapter 1 - Exploring Kotlin for Android App development

Welcome to Kotlin World !!!



What Kotlin means ?



Kotlin is a statically typed programming language and development language from JetBrains which is the company behind the IntelliJ Java IDE (i.e. Android Studio is based on) that runs on the Java virtual machine and also can be compiled to JavaScript source code.


Note : Kotlin isn't a programming language on its own; it's a new way to write code that uses Java to run.


At Google I/O 2017 in April, Google announced that Kotlin would forever more be supported as a first class programming language for Android. And the recently released Android Studio 3.0 supports Kotlin out of the box!

Why Kotlin is good?


  • Kotlin comes from industry, not academia. It solves problems faced by working programmers today.
  • Kotlin costs nothing to adopt! It’s open source, a high quality, one-click Java to Kotlin converter tool, and a strong focus on Java binary compatibility. You can convert an existing Java project one file at a time.
  • No particular philosophy of programming, such as overly functional or OOP styling and also Semicolon free language.
  • Kotlin programs can use all existing Java frameworks and libraries, even advanced frameworks that rely on annotation processing. 
  • No runtime overhead. The standard library is small and tight: it consists mostly of focused extensions to the Java standard library. 
  • No new keyword while initialization any object.  


Getting started with Android and Kotlin


Let walk through creating a simple Kotlin application for Android using Android Studio.

Installing the Kotlin plugin



The Kotlin plugin is bundled with Android Studio starting from version 3.0.

If you use an earlier version, you'll need to install the Kotlin plugin. Go to File | Settings | Plugins | Install JetBrains plugin… and then search for and install Kotlin.

If you are looking at the "Welcome to Android Studio" screen, choose Configure | Plugins | Install JetBrains plugin after that restart the IDE.

First let's create a new project. Choose Start a new Android Studio project or File | New project.
Android Studio 3.0 offers an option to enable Kotlin support on this screen. You can check this option and skip the "Configuring Kotlin in the project".



In Android Studio 3.0, you can choose to create the activity in Kotlin right away, so you can skip the "Converting Java code to Kotlin" step. Earlier versions will create an activity in Java, and you can use the automated converter tool to convert it.

Building and publishing the Kotlin application for Android


You can make a release of the application and sign it similarly to what you do for an Android application written in Java. Kotlin has a rather small runtime file size: the library is approximately 964KB. This means Kotlin adds just a little to .apk file size.

Kotlin compiler produces byte-code, thus there really is no difference in terms of look and feel of Kotlin applications versus those written in Java.

How Kotlin stands out ?


Kotlin is directly filled the gap of modern programming language for Android application development like how Swift language does for iOS development.


1. Concise to reduce the amount of boilerplate code you need to write.
We can create a POJO with getters, setters, equals(), hashCode(), toString(), and copy() with a single line.
  • No need hashCode(), equals(), toString(), and copy()
  • Compiler automatically create these internally, so it also leads to clean code.

data class Developer(val name: String, val age: Int)
Requirements that data classes need to fulfil:
  • The primary constructor needs to have at least one parameter.
  • All primary constructor parameters need to be marked as val or var
  • Data classes cannot be abstract, open, sealed or inner.

2. No null pointer exceptions (NPE) in Kotlin
Kotlin type system helps you avoid null pointer exceptions (NPE). Research languages tend to just not have null at all, but this is of no use to people working with large codebases and APIs which do.
We have to write safer code to avoid NullPointerExceptions in our app.
var message: String = null      // Compile-time error
var message: String? = null     // Okay
If something is null, I want to give it a value, but otherwise just leave it alone.
// Java
           if (people == null) {
               people = new ArrayList();
           }
           return people;
// Kotlin
           return people ?: emptyArrayList()
The Elvis Operator (?:) looks like the ternary conditional operator in Java, but works differently.
If you’re absolutely sure a nullable object is not null, feel free to use the !! operator to dereference your object.
tabLayout = findViewById<TabLayout>(R.id.tabs)
        tabLayout!!.setupWithViewPager(viewPager)

3. No need findViewById using android-extensions
Kotlin (specifically Android Extensions) do the heavy lifting for you. apply plugin: 'kotlin-android-extensions' in app.gradle
For the layout filename activity_main.xml, we'd need to import
import kotlinx.android.synthetic.main.activity_main.*
txtTitle.text = "Hello Kotlin"
There is no more view binding. Internally the compiler creates a small hidden cache. Moreover Activity or Fragment giving us the synthetic property to use the view. Lazy initialized i.e. when you use the view in the code. Next time you use the same view it will fetch it from cache.

4. Zero-overhead lambdas
Functional programming support with zero-overhead lambdas and ability to do mapping, folding etc over standard Java collections. The Kotlin type system distinguishes between mutable and immutable views over collections.
Higher Order Function - passed as an argument to another function. Beautifying even the ugliest click handlers,
mButton.setOnClickListener {
   // Your click logic
}
Cut to the main logic & code so clean and simple.

5. 100% inter-operable with Java™ (Automatic conversion)
Interoperable to leverage existing frameworks and libraries of the JVM with 100 percent Java interoperability.
Kotlin is a programming language made by developers for developers, it’s designed to make your life as easy as possible. The Kotlin plugin even has a handy tool that allows you to convert a Java source file to Kotlin.
Open the DetailActivity.java class and go to Code\Convert Java File to Kotlin File.




Click OK on the Convert Java to Kotlin screen. This will replace the Java file with a Kotlin. That’s it. You’ve converted a Java class into a Kotlin class.

6. Extend function without extends or implement keyword
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
  }
}
Inheritance- No “extends” & “implements”, Replaced with a “:”

7. Free Functions (Functions without belong to any class)
Functions or variables can be declared at the top level in a file (*.kt) without any class. By default static in nature without any class holding them.
We can write free functions and access them from another Kotlin class or file directly (without Class name). But, functions come with access specifiers to control the visibility.

8. No if/else if/else/switch blocks
Replacing simple if/else if/else/switch blocks with ‘when’ keyword
In JAVA

  if (firstName.equals("Dan")) {
               person.setTeam(programmers);
           } else if (lastName.equals("Dihiansan")) {
               person.setTeam(designers);
           } else {
               person.setTeam(others);
           }

switch (firstName) {
               case "Dan": person.setTeam(programmers)
               break;
               case "Jay": person.setTeam(programmers)
               break;
               case "Jamie": person.setTeam(designers)
               break;
               default:
               person.setTeam(others)
           }

In Kotlin
when {
               firstName == "Dan"       -> person.team = programmers
               lastName == "Dihiansan" -> person.team = designers
               else         -> person.team = others
           }

when (firstName) {
               "Dan", "Jay" -> person.team = programmers
               "Jamie" -> person.team = designers
               else -> person.team = others
           }


9. apply() for Grouping Object Initialization
//Don't
val dataSource = BasicDataSource()
           dataSource.driverClassName = "com.mysql.jdbc.Driver"
           dataSource.url = "jdbc:mysql://domain:3309/db"
           dataSource.username = "username"
           dataSource.password = "password"
//Do
           val dataSource = BasicDataSource().apply {
               driverClassName = "com.mysql.jdbc.Driver"
               url = "jdbc:mysql://domain:3309/db"
               username = "username"
               password = "password" }

It helps to group and centralize initialization code for an object. apply() is often useful when dealing with Java libraries in Kotlin.

10. Returning Two Values from a Function
Destructuring is the convenient way of extracting multiple values from data.


fun getDeveloper(): Developer {
// some logic
return Developer(name, age)
}
val (name, age) = getDeveloper()
// do something with the key and the value
}
data class Developer(val name: String, val age: Int)
// Now, to use this function: Destructuring Declarations and Maps
for ((key, value) in map) {}
Hope I covered some basic cool stuffs about Kotlin programming language. I have developed sample Android application with Android key features in Kotlin. I keep updating in next chapters of Kotlin.

References


Kotlin interactive programming  
Happy Coding !!!!