Base64 Encoding in Scala
Scala provides built-in support for base64 encoding/decoding.
import java.util.Base64
import java.nio.charset.StandardCharsets
object Base64Encoding {
def main(args: Array[String]): Unit = {
// Here's the string we'll encode/decode.
val data = "abc123!?$*&()'-=@~"
// Scala supports both standard and URL-compatible
// base64. Here's how to encode using the standard
// encoder.
val sEnc = Base64.getEncoder.encodeToString(data.getBytes(StandardCharsets.UTF_8))
println(sEnc)
// Decoding may return an error, which you can catch
// if you don't already know the input to be
// well-formed.
val sDec = new String(Base64.getDecoder.decode(sEnc), StandardCharsets.UTF_8)
println(sDec)
println()
// This encodes/decodes using a URL-compatible base64
// format.
val uEnc = Base64.getUrlEncoder.encodeToString(data.getBytes(StandardCharsets.UTF_8))
println(uEnc)
val uDec = new String(Base64.getUrlDecoder.decode(uEnc), StandardCharsets.UTF_8)
println(uDec)
}
}
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.
$ scala Base64Encoding.scala
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
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.