Created
January 30, 2017 08:37
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 equalemptyLocation()
if there is no location in the Intent