Safeguarding Collections and Object References with Scala's Option

Search for a command to run...

No comments yet. Be the first to comment.
Go's race detector samples a schedule and hopes. GALA makes a value that isn't safe to share across goroutines a build failure.
June's 0.56 -> 0.62 releases: bind/also monadic do-notation, applicative validation with Validated, and concurrent binds over Future.
Importing a third-party Go module through Bazel and rules_gala - with concrete types across the seam, verified hands-on.
From rules welded inside the language repo to a standalone, registry-published rules_gala with a real toolchain and Gazelle BUILD generation.
Eleven weeks, ~55 releases, and a new tagline: GALA hits 0.50.0 with cross-package generics, an LSP, and four new stdlib packages.
We often use Option to handle collections safely:
val collection = Map.empty[Int, Int]
// unsafe way that will throw an exception if key is not present
val value = collection(1)
// safe way
val valueOpt = collection.get(1) match {
case Some(value) => // key is present
case None => // key is not present
}
In Scala, object references can have a value of null. That makes them unsafe. Bugs, that are related to unsafe calls, are very hard to detect. Luckily, the Option class can help to handle them for free:
var mutableRef: Car = null
Option(mutableRef) match {
case Some(value) => // non-null
case None => // null
}
This also lets us use Option composition to make safe calls:
class Car() {
val width: Int = 100
}
var mutableRef: Car = null
// unsafe way that will throw an exception if mutableRef is null
val carWidth = mutableRef.width
// safe way
val carWidthOpt = Option(mutableRef).map(_.width)
Scala's Option class provides a powerful way to handle null values and safeguard collections and object references, minimizing the risk of bugs related to unsafe calls. By utilizing Option composition, developers can create more robust and maintainable code, ensuring a safer and more efficient development experience.