Scala

Scala

Made by DeepSource

Redundant getOrElse() on get() SC-R1005

Anti-pattern
Minor

get() is used to index data structures such as Map to retrieve values. Such structures also provide an additional method, getOrElse(), that additionally allows you to provide a default value to use if the requested key is nonexistent. While get() returns an Option[Type] which may be Some(value) or None depending on whether the value exists, getOrElse() will directly return a value of the correct type. If you need to supply a default value for nonexistent entries, it is more succinct and maintainable to use getOrElse() on the collection itself instead of chaining getOrElse() after get().

Bad practice

val requiredValue = map.get(key).getOrElse(alternativeValue)

Recommended

val requiredValue = map.getOrElse(key, alternativeValue)