Published in


Kotlin — Shortcut for development!

Well kotlin is certainly one of the best languages out there which not only reduces the time and effort of the developer with it’s handy features but also help to keep code neat and clean. So let’s have a look on the exciting usage of kotlin for developing android app.

Load Fragment
In case you want to load fragment than it’s important to commit the transaction and in case you forget it than studio do gives warning but there should be some better way to fix it rather than manually adding commit to your transactions. So let’s see how higher order function can help out .

fun loadFragment(loadToBackStack:Boolean = false,
load: FragmentTransaction.() -> Any) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
val fragmentName = fragmentTransaction.load()

if (loadToBackStack) {

So now it’s easy to load fragment with no worries about remembering stuffs like beginTransaction, addToBackStack and commit. All those things are done in the simple higher order function. About calling this function then there are two ways:

//Load fragment with no back stack entry
loadFragment { replace(, Fragment1())}

//load fragment with back stack entry
loadFragment(true) { replace(, Fragment1())}

Show Alert Dialog
Showing alert dialog is one such area which requires a lot of attention. Most often the show method gets missed out resulting in not displaying any alert on UI so higher order function can handle this thing also.

fun showAlert(showAlertDialog: AlertDialog.Builder.() -> Any) {
val dialogBuilder = AlertDialog.Builder(this)

fun AlertDialog.Builder.positiveButton(name: String = "Okay", clickListener: (which: Int) -> Any = {}) {
{ _, which -> clickListener(which) })

fun AlertDialog.Builder.negativeButton(name: String = "Cancel", clickListener: (which: Int) -> Any = {}) {
{ _, which -> clickListener(which) })

Here showAlert is the higher order function which will be used to set title, message, button for the alert dialog. Whereas AlertDialog.Builder.positiveButton and AlertDialog.Builder.negativeButton are extension and higher order function which will be used along with showAlert method. These two methods avoid the need to passing listener for the positive and negative button. Here are it’s usage

showAlert {
setMessage("My Message")
positiveButton { Toast.makeText(this@MainActivity,"It's positive button",Toast.LENGTH_SHORT).show() }

positiveButton() is an extension higher order function which takes two parameter first is the name of the button and second is some other function. Here we are not passing name of the button because of the default argument which take button name as “Okay” when no value is passed.

Sort HashMap
Sorting a hashMap could never been so easy as it is now. To sort a hashMap the following procedure is needed. Convert the hashMap to list than sort the list thereafter convert it back to Map.

val hash = HashMap<String, Int>()
//Sort hashMap based on key
hash.toList().sortedBy { (key,value)-> key }.toMap()
//Sort hashmap based on value
hash.toList().sortedBy { (key,value)-> value }.toMap()

High Order function for Constants
There are cases where some common constants are used in lots of places and if it’s written inside the subclass of constants class than every time need to write constant.subclass.CONSTANT_NAME but this is quite tedious when need to write more often so there is way to avoid this scenario with higher order function

object Constants {
object Common {
val ONE = "1"
val TWO
= "2"
= "3"

Constant.Common.ONE is tradition way to fetch the constant value of ONE
So let’s see how kotlin will handle this

fun common(constants: Constants.Common.() -> String): String {
val common = Constants.Common
return common.constants()

Write this higher order function and create a function call till Constant.Common as we are interested in fetching the values inside Common only.

Now to fetch the constant value ONE just write this

common { ONE }

Java: Constant.Common.ONE
Kotlin: common { ONE }

Certainly with wide usage of common constant this may save time and effort.

Apply to save time
One of the most tedious task is to repeatedly writing an object name so as to get it’s members but with apply this can be avoided. On whichever object apply is called all it’s member thereafter can be accessed directly without writing the object name again and again.

//Without using apply
//With apply
user.apply {

But hold on, what if I have two objects and I need them at a same time

user.apply {
emp.also {

Well to handle that kind of scenario combination of apply and also works well. One point to remember here is that apply makes it’s member available with this keyword whereas also makes them available with it keyword. Where writing this before accessing the member is optional but when using also than it’s mandatory to access member through it keyword.

Hope you all have like these handy features of kotlin which make development even easier.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store