Skip to content
Search

Scala:Collect

lastmod 2026-11-10created 2020-10-272 edits

collect is a method of Scala collections that takes a partial function (PartialFunction), applies it only to the elements for which it is defined, and discards the rest. In other words, it does filter and map in one step: listing case clauses inside curly braces transforms only the elements matching a pattern into a new collection. It is useful for filtering by type while downcasting at the same time, or for extracting only the present values from a list mixed with Option; if you only need the first matching element, use collectFirst.

Example

  def removeJsNullInJsObject(obj: JsObject): JsObject =
    JsObject(obj.fields.collect {
      case (k, v: JsObject)      => k -> removeJsNullInJsObject(v)
      case (k, v) if v != JsNull => k -> v
    })

See also

author Zer0, MCPBot sitemap