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
Why do we need to encode? URLs can only have certain characters from the standard 128 character ASCII set. Reserved characters that do not belong to this set must be encoded. This means that we need to encode these characters when passing them into a URL.
%20 is an encoded ' ' (blank). %26 is an encoded '&' (ampersand). See "HTML URL Encoding Reference"[^]. Instead of removing them, you probably should convert them back to blank and ampersand instances.
URL Encoding is used when placing text in a query string to avoid it being confused with the URL itself. It is normally used when the browser sends form data to a web server. URL Encoding replaces “unsafe” characters with '%' followed by their hex equivalent.
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"
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With