Base64 Encoding in Kotlin
Here’s the translation of the Base64 Encoding example from Go to Kotlin, formatted in Markdown suitable for Hugo:
Kotlin provides built-in support for base64 encoding/decoding.
The string encodes to slightly different values with the standard and URL base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.
In Kotlin, we use the java.util.Base64
class for base64 encoding and decoding. The getEncoder()
and getDecoder()
methods are used for standard base64, while getUrlEncoder()
and getUrlDecoder()
are used for URL-safe base64.
The encodeToString()
method is used to encode a ByteArray to a base64 String, and decode()
is used to decode a base64 String back to a ByteArray. We convert between String and ByteArray using toByteArray()
and the String constructor that takes a ByteArray, respectively.
Note that in Kotlin, we don’t need to explicitly handle errors when decoding, as the decode()
method throws an IllegalArgumentException if the input is not properly encoded.