Build and parse URL query strings in Kotlin
Kotlin
import java.net.URLDecoder
import java.net.URLEncoder
fun encodeQuery(params: Map<String, String>): String =
params.entries.joinToString("&") { (k, v) ->
URLEncoder.encode(k, "UTF-8") + "=" + URLEncoder.encode(v, "UTF-8")
}
fun parseQuery(query: String): Map<String, String> =
query.removePrefix("?").split('&').filter { it.isNotEmpty() }.associate { pair ->
val i = pair.indexOf('=')
val key = if (i < 0) pair else pair.substring(0, i)
val value = if (i < 0) "" else pair.substring(i + 1)
URLDecoder.decode(key, "UTF-8") to URLDecoder.decode(value, "UTF-8")
}
val q = encodeQuery(mapOf("q" to "kotlin coroutines", "page" to "2"))
check(parseQuery(q)["q"] == "kotlin coroutines")