Base64 Encoding in Scala
Scala 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 this Scala version:
We import
java.util.Base64
andjava.nio.charset.StandardCharsets
for base64 encoding/decoding and character encoding, respectively.We define an object
Base64Encoding
with amain
method, which is the entry point of our program.For standard base64 encoding and decoding, we use
Base64.getEncoder
andBase64.getDecoder
.For URL-safe base64 encoding and decoding, we use
Base64.getUrlEncoder
andBase64.getUrlDecoder
.We convert strings to byte arrays using
getBytes(StandardCharsets.UTF_8)
and back to strings usingnew String(..., StandardCharsets.UTF_8)
to ensure proper character encoding.Error handling in Scala is typically done using
Try
or exceptions, but for simplicity, we’ve omitted explicit error handling in this example.
This Scala code achieves the same functionality as the original example, demonstrating both standard and URL-safe base64 encoding and decoding.