Skip to content

Instantly share code, notes, and snippets.

@antonis
Created December 20, 2019 14:11
Show Gist options
  • Select an option

  • Save antonis/758d7de541ef32bccf03a44bc5db27a9 to your computer and use it in GitHub Desktop.

Select an option

Save antonis/758d7de541ef32bccf03a44bc5db27a9 to your computer and use it in GitHub Desktop.
Fetches exchange rate from the European Central Bank https://exchangeratesapi.io
import com.google.gson.Gson
import com.google.gson.JsonObject
enum class CurrencySymbol {
EUR, CAD, HKD, ISK, PHP, DKK, HUF, CZK, AUD, RON, SEK,
IDR, INR, BRL, RUB, HRK, JPY, THB, CHF, SGD, PLN, BGN,
TRY, CNY, NOK, NZD, ZAR, USD, MXN, ILS, GBP, KRW, MYR
}
/**
* Fetches exchange rate from the European Central Bank https://exchangeratesapi.io
* @param base base currency
* @param currency target currency
* @return The exchange rate
*/
fun getRate(base: CurrencySymbol, currency: CurrencySymbol): Double? {
return try {
val url = "https://api.exchangeratesapi.io/latest?base=$base&symbols=$currency"
val json = java.net.URL(url).readText()
val jsonObject = Gson().fromJson<JsonObject>(json, JsonObject::class.java)
jsonObject["rates"].asJsonObject[currency.name].asDouble
} catch (e: Exception) {
null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment