Simplified code with kotlin

Pankaj Rai 🇮🇳
AndroidPub
Published in
4 min readDec 6, 2017

--

Kotlin is undoubtedly a very popular language with it’s vast coverage to Java, Android App, JavaScript it’s currently in hot trend and what makes kotlin so popular is the ability to get more with less code. So let’s see some simple yet effective code in kotlin.

Parcelable
Now have automatic parcelable implementation with @Parcelize annotation.

@Parcelize
class Users(val name:String, val age:Int): Parcelable

In order to use this feature add this to your app gradle

apply plugin: 'kotlin-android-extensions'android {
....
androidExtensions {
experimental = true
}
}

Array of 100 element:
In java the straightforward way to have array of first 100 natural number is to either initialize at the time of declaration (int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10…100};) but this is surely not an optimal way or using for loop which is quite optimal like below for example

private int[] numbers = new int[100];

void setNumbers() {
for (int index = 0; index < 100; index++) {
numbers[index] = index + 1;
}
}

Now let’s see same in kotlin with just a single line

private val numbers = Array(100, {x -> x + 1})

Alert Dialog with higher order function
Well sometime it’s okay not to create a callback to handle alert dialog button click rather why should even I create callback when my default action is just to dismiss alert dialog when a button is pressed. So here is the super simplified solution to avoid callbacks

fun showAlertDialog(dialogBuilder: AlertDialog.Builder.() -> Unit) {
val builder = AlertDialog.Builder(this)
builder.dialogBuilder()
val dialog = builder.create()

dialog.show()
}

fun AlertDialog.Builder.positiveButton(text: String = "Okay", handleClick: (which: Int) -> Unit = {}) {
this.setPositiveButton(text, { dialogInterface, which-> handleClick(which) })
}

fun AlertDialog.Builder.negativeButton(text: String = "Cancel", handleClick: (which: Int) -> Unit = {}) {
this.setNegativeButton(text, { dialogInterface, which-> handleClick(which) })
}

Have this methods in the BaseActivity thereafter call in any activity directly.
To show alert dialog simply call showAlertDialog() method

showAlertDialog {
setTitle("Greet")
setMessage("Welcome again, want coffee?")
positiveButton("Yes") {
showToast("Clicked on Yes")
}

negativeButton {
showToast("Clicked on cancel")
}
}

Short Toast Message
It’s so common to use toast message especially during development and most of the time duration of toast message is short so why not to use default parameter to handle short duration of toast.

fun showToast(msg: String, toastDuration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this,msg, toastDuration).show()
}

Now when duration is short just call showToast(“Some message here”) and when duration is long then showToast(“Some message here”, Toast.LENGTH_LONG)

Filter Data
To filter data from an array there is a straightforward way just by using lambda functions.

numbersList
.filter{it % 2 == 0}
.forEach{print(it)}

This will print only even numbers from the list

Late Initialization
All global variable need to be initialized at the time of declaration but sometime it’s tedious to initialize variable with either some dummy value or with null just because initialization is mandatory so here is the trick to avoid initialization just by using lateinit

private lateinit var mCity:String

One important thing is all variable declared with lateinit keyword has to be initialized first before being used otherwise app will crash. With kotlin 1.2 a feature is included to check weather variable is initialized or not by using isInitialized method eg: mCity.isInitialized

Lazy Loading — Delegate
Well why not to load content on demand rather than just loading all content at an activity launch. Lazy loading is one such mechanism where variable is initialized when it’s being used for the first time thereafter same value will be used for all further usage and it cannot be re-initialized with some other value

private val mIntent:Intent by lazy { 
Intent()
}

Whenever mIntent is called for the first time it will be initialized with Intent()

Observable — Delegate
That’s one such delegate method which observe for the changes and provides both old and new value on whomever this observable is set on

private var mName by Delegates.observable("some_initial_value"){
property, oldValue, newValue -> print("Old Value:${oldValue} New Value:${newValue}")
}

Now whenever mName value get modified it will print it’s old and new value.

Let’s see some practical usage like counting the length of the string using observable delegate

private var mNameLength:Int = 0
private var mName by Delegates.observable("some_initial_value"){
property, oldValue, newValue -> mNameLength = newValue.length
}

Now whenever mName value is modified mNameLength gets calculated automatically.

Elegant Infix
Wouldn’t be nice to write method name and pass parameter to it just by leaving space instead of traditional way of calling a function like in below example

infix private fun Int.addNumber(number: Int) {
this.plus(number)
}
//Calling addNumber extension function here
100 addNumber 5

Kotlin comes with great set of features with kotlin 1.2 even cross platform support is also available, write code at once and run on both java & javascript platform.

--

--

Pankaj Rai 🇮🇳
AndroidPub

Software Engineer | GDE Android & Firebase | YouTuber — All Techies