mongo-java-driver icon indicating copy to clipboard operation
mongo-java-driver copied to clipboard

Add optional casting methods

Open jeffalder opened this issue 1 year ago • 0 comments

Because BsonValue has boolean is methods, and throwing as methods, a common pattern is:

BsonValue value;
if (value.isSomeType()) {
  BsonSomeType valueSomeType = value.asSomeType();
  // .. operate on valueSomeType
}

Nested conditionals are even harder:

BsonValue value;
if (value.isDocument() && value.asDocument().get("key").isInt32()) {
  //... dig in and get it
}

By using Java 8's Optional, we can simplify these with a fluent syntax:

BsonValue value;
value.asSomeTypeOpt().ifPresent(valueSomeType => {
  // valueSomeType is guaranteed to be BsonSomeType
});

Optional<BsonInt32> nested = value.asDocumentOpt()
  .flatMap(doc => doc.get("key").asInt32Opt());

I can also add get*Opt methods to BsonDocument if they make sense.

jeffalder avatar Aug 01 '24 21:08 jeffalder