My Android Kotlin Tips

Hello guys, as an Android developer, started using Kotlin for Android projects late in 2016 , I’ve got some tips for sharing you today.

  1. Initial Kotlin Tips for Android :

I reconigized several benefits to lazy loading. Lazy loading can result in faster startup time, since loading is deferred to when the variable is accessed. Lazy loading like this is also more memory efficient , as we only load the resource into memory if it is called upon. I give you an example for lazy loading:

val purchasingApi: PurchasingApi by lazy {
    val retrofit: Retrofit = Retrofit.Builder()
            .baseUrl(API_URL)
            .addConverterFactory(MoshiConverterFactory.create())
            .build()
    retrofit.create(PurchasingApi::class.java)
}

By using lazy loading like this, if the user never attempts to check out in the app, you will never load the PurchasingApi, therefore will not use up the resource it would take.

Lazy loading is also a good way to encapsulate initialization logic :

// bounds is created as soon as the first call to bounds is made
val bounds: RectF by lazy { 
    RectF(0f, 0f, width.toFloat(), height.toFloat()) 
}

As soon as the first reference to bounds is made, the RectF is created, using the view’s current width and height , saving us from having to explicitly create this RectF, the set it later on.

2. Custom Getters/Setter

Kotlin’s custom getters and setters use the structure of a model , but specify custom behavior to get and set the fields.

@ParseClassName("Book")
class Book : ParseObject() {

    // getString() and put() are methods that come from ParseObject
    var name: String
        get() = getString("name")
        set(value) = put("name", value)

    var author: String
        get() = getString("author")
        set(value) = put("author", value)
}

Fetching these values would look similar to using property access syntax with other models:

val book = api.getBook()
textAuthor.text = book.author

Now if your model needed to change from Parse to some other data source, your code would potentially only need to be changed in one place.

3. Lambdas

Lambdas reduce the overall lines of code in a souce and allow for funcational programming . While lambdas are currently possible with Android, Kotlin take them a step further byu ensuring you don’t have to deal with RetroLambda or chaning the way your build is configured

For example, an on-click listener would look like:

button.setOnClickListener { view ->
    startDetailActivity()
}

It even works with return values:

toolbar.setOnLongClickListener { 
    showContextMenu()
    true
}

4. Data Classes

Data classes simplify classes, adding equals(), hashcode(), copy(), toString() methods automatically.

data class User(val name: String, val age: Int)

That’s it. Nothing else is needed to make this class work. If you are using data classes with something like Gson or another JSON parsing library , you can create the default constructor with default values like so:

// Example with Gson's @SerializedName annotation
data class User(
    @SerializedName("name") val name: String = "",
    @SerializedName("age") val age: Int = 0
)

 5. Global Constants

Kotlin allows you to define constants that span across an entire app in one place . By using ” const val ”

package com.savvyapps.example

import android.support.annotation.StringDef

// Note that this is not a class, or an object
const val PRESENTATION_MODE_PRESENTING = "presenting"
const val PRESENTATION_MODE_EDITING = "editing"

These can be used as constants anywhere in your project:

 

import com.savvyapps.example.PRESENTATION_MODE_EDITING

val currentPresentationMode = PRESENTATION_MODE_EDITING


Leave a comment