Mia
Mia

Reputation: 319

How to do url encoding for query parameters in Kotlin

I am new to Kotlin & I am trying to url encode my url which has query parameters.

private const val HREF = "date?July 8, 2019"
private const val ENCODED_HREF = print(URLEncoder.encode(HREF, "utf-8"))
private const val URL = "www.example.com/"+"$ENCODED_HREF"

Error: Const 'val' has type 'Unit'. Only primitives and Strings are allowed for private const val ENCODED_HREF

Upvotes: 21

Views: 45975

Answers (2)

David P. Caldwell
David P. Caldwell

Reputation: 3831

const expressions in Kotlin must be known at compile time. Also, as @Stanislav points out, print is a Unit (i.e., void in Java) method, so printing something destroys its value.

Since your constants are computed, the use of val (which is a runtime constant) is appropriate. The following compiles.

private const val HREF = "date?July 8, 2019"
private val ENCODED_HREF = java.net.URLEncoder.encode(HREF, "utf-8")
private val URL = "www.example.com/"+"$ENCODED_HREF"

Upvotes: 29

Stanislav Shamilov
Stanislav Shamilov

Reputation: 1826

Seems like the returning type of the print method is Unit, so that's why ENCODED_HREF has this type. Just take the URLEncoder part out of the method to fix it:

private const val ENCODED_HREF = URLEncoder.encode(HREF, "utf-8")

Upvotes: 13

Related Questions