Android KTX :- Sweeter kotlin for android

Android KTX :- Sweeter kotlin for android

Google announced android-ktx, which is a set of Kotlin extensions for Android app development. The goal of this sweet killer is to make, kotlin code for Android more concise, idiomatic, and pleasant.

https://youtu.be/kmvS3sZF_y0

Android KTX provides a nice API layer on top of both Android framework and Support Library to make writing your Kotlin code more natural.

Now, the library is only in the preview so it is likely to change – try it out to give your feedback and contributions.

The documentation for KTX can be found here :

and the library is here :

Let’s take a look at some examples of how Android KTX can help you write more natural and concise Kotlin code.

Getting Started :-

To add android KTX to your project add dependencies in your build.gradle file

repositories {
    google()
}

dependencies {
    implementation 'androidx.core:core-ktx:0.1'
}

Then in your kotlin file import appropriate package and enjoy the coding.

This project will not add any new feature to existing android API. This are the wrapper APIs for android kotlin, this makes kotlin developer life more simple.

String to URI

Kotlin:

val uri = Uri.parse(myUriString)

Kotlin with Android KTX:

val uri = myUriString.toUri()

The simple shared Preference

Kotlin:

sharedPreferences.edit()
    .putBoolean("key", value)
    .apply()

Kotlin with Android KTX:

sharedPreferences.edit {
    putBoolean("key", value)
}

If you are canvas lover

Kotlin:

val pathDifference = Path(myPath1).apply {
    op(myPath2, Path.Op.DIFFERENCE)
}
canvas.apply {
  val checkpoint = save()
  translate(0F, 100F)
  drawPath(pathDifference, myPaint)
  restoreToCount(checkpoint)
}

Kotlin with Android KTX:

val pathDifference = myPath1 - myPath2
canvas.withTranslation(y = 100F) {
    drawPath(pathDifference, myPaint)
}

This is the AndroidX. Add this extension to your tool suite.

Let us apply thoughts and let me know your experience.

If you enjoyed this article, please don’t forget to Clap.

For more stories.

Lets connect on Stackoverflow , LinkedIn , Facebook& Twitter.