Skip to content

Instantly share code, notes, and snippets.

@nmwilk
Created January 30, 2017 08:37
Show Gist options
  • Save nmwilk/892886094a3f3a2cebe5a46015980e35 to your computer and use it in GitHub Desktop.
Save nmwilk/892886094a3f3a2cebe5a46015980e35 to your computer and use it in GitHub Desktop.
Example of using Kotlin extension functions to reduce boilerplate when dealing with Android Intents.
package com.carte_app.carte.util
import android.content.Intent
fun Intent.addLocation(location: Location): Intent {
putExtra(IntentExtensions.INTENT_PARAM_LOCATION_LAT, location.lat)
putExtra(IntentExtensions.INTENT_PARAM_LOCATION_LNG, location.lng)
return this
}
fun Intent.location(): Location {
val lat = getDoubleExtra(IntentExtensions.INTENT_PARAM_LOCATION_LAT, Location.EMPTY_VALUE)
val lng = getDoubleExtra(IntentExtensions.INTENT_PARAM_LOCATION_LNG, Location.EMPTY_VALUE)
return Location(lat, lng)
}
class IntentExtensions {
companion object {
val INTENT_PARAM_LOCATION_LAT = "t3ikl3n"
val INTENT_PARAM_LOCATION_LNG = "tygvwewdf"
}
}
data class Location(val lat: Double, val lng: Double) {
companion object {
val EMPTY_VALUE = Double.MAX_VALUE
fun emptyLocation() = Location(EMPTY_VALUE, EMPTY_VALUE)
}
}
@nmwilk
Copy link
Author

nmwilk commented Jan 30, 2017

To add a location to an Intent:

intent.addLocation(Location(lat, lng))

To get a location from an Intent:

val location = intent.location()

location will equal emptyLocation() if there is no location in the Intent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment